【问题标题】:swift init not visible in objective-Cswift init 在 Objective-C 中不可见
【发布时间】:2014-12-15 17:42:20
【问题描述】:
【问题讨论】:
标签:
objective-c
uitableview
swift
【解决方案1】:
您看到的问题是 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 也是可选参数,否则您将通过这种方式设置自己以应对潜在的运行时崩溃。
【解决方案2】:
使用这个:
var index: NSInteger!
@objc convenience init(index: NSInteger) {
self.init()
self.index = index
}