【问题标题】:swift init not visible in objective-Cswift init 在 Objective-C 中不可见
【发布时间】:2014-12-15 17:42:20
【问题描述】:

我正在尝试在Swift 中创建init 函数并从Objective-C 创建实例。问题是我在Project-Swift.h 文件中看不到它,并且在初始化时我无法找到该函数。我有一个定义如下的函数:

public init(userId: Int!) {
    self.init(style: UITableViewStyle.Plain)
    self.userId = userId
}

我什至尝试输入@objc(initWithUserId:),但我再次收到同样的错误。还有什么我想念的吗?如何让 Objective-C 代码可以看到构造函数?

我为此阅读了以下内容:

https://developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/Initialization.html

https://developer.apple.com/library/ios/documentation/swift/conceptual/buildingcocoaapps/interactingwithobjective-capis.html

How to write Init method in Swift

How to define optional methods in Swift protocol?

【问题讨论】:

    标签: objective-c uitableview swift


    【解决方案1】:

    您看到的问题是 Swift 无法桥接可选值类型——Int 是值类型,因此无法桥接 Int!。可选引用类型(即任何类)正确桥接,因为它们在 Objective-C 中始终可以是 nil。您的两个选项是使参数成为非可选参数,在这种情况下,它将作为 intNSInteger 桥接到 ObjC:

    // Swift
    public init(userId: Int) {
        self.init(style: UITableViewStyle.Plain)
        self.userId = userId
    }
    
    // ObjC
    MyClass *instance = [[MyClass alloc] initWithUserId: 10];
    

    或者使用可选的NSNumber?,因为它可以作为可选值桥接:

    // Swift
    public init(userId: NSNumber?) {
        self.init(style: UITableViewStyle.Plain)
        self.userId = userId?.integerValue
    }
    
    // ObjC
    MyClass *instance = [[MyClass alloc] initWithUserId: @10];    // note the @-literal
    

    但是,请注意,您实际上并没有将参数视为可选参数 - 除非 self.userId 也是可选参数,否则您将通过这种方式设置自己以应对潜在的运行时崩溃。

    【讨论】:

      【解决方案2】:

      使用这个:

      var index: NSInteger!
      
      @objc convenience init(index: NSInteger) {
          self.init()
      
          self.index = index
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多