swift init在objective-C中不可见

我正在尝试在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?

你看到的问题是Swift无法桥接可选的值类型 – Int是一个值类型,所以Int!无法弥合.可选的引用类型(即任何类)正确桥接,因为它们在Objective-C中始终为nil.您的两个选项是使参数非可选,在这种情况下,它将作为int或NSInteger桥接到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也是一个可选参数,您可以通过这种方式设置自己的潜在运行时崩溃.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...