2014-10-20 29 views
18
中不可见

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

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?

回答

26

你看到的问题是,斯威夫特无法弥合可选值类型 - Int是一个值类型,所以Int!不能被桥接。可选的参考类型(即任何类)桥,因为它们在Objective-C中始终可以是nil。你的两个选项是使参数不可选的,在这种情况下,它可以通过交联ObjC为intNSInteger

// 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也是可选的,你就把自己潜在的运行崩溃这样。

相关问题