【问题标题】:How to use swift struct as property in Objective-c protocol?如何在 Objective-c 协议中使用 swift struct 作为属性?
【发布时间】:2016-03-24 09:46:20
【问题描述】:

我有 Objective-c 协议。在这个协议中,我需要声明一个 Swift 结构类型的属性。如何实现这一点?

SomeObjectiveCProtocol.h:

@protocol SomeObjectiveCProtocol <NSObject>
    @property (nonatomic, readonly) SomeSwiftStruct swiftStruct;
@end

这样的事情可能吗?

【问题讨论】:

    标签: objective-c swift swift2


    【解决方案1】:

    您可以使用协议_ObjectiveCBridgeable 将 Swift 结构转换为 Obj-C 类。看这个例子(我还没有测试过):

    Easy Cast With _ObjectiveCBridgeable

    【讨论】:

      【解决方案2】:

      我通过协议的前向声明来解决这个问题。我定义了

      一些SwiftProtocol.swift:

      protocol SomeSwiftProtocol {
          // some protocol requirements
      }
      

      SomeSwiftStruct.swift:

      struct SomeSwiftStruct: SomeSwiftProtocol {
          // SomeSwiftProtocol implementation
      }
      

      比在 SomeObjectiveCProtocol.h 中:

      @protocol SomeSwiftProtocol;
      
      @protocol SomeObjectiveCProtocol <NSObject>
          @property (nonatomic, readonly) id<SomeSwiftProtocol> swiftStructProtocol;
      @end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-01
        • 2016-07-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多