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也是一个可选参数,您可以通过这种方式设置自己的潜在运行时崩溃. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |