2014-10-20 30 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也是可選的,你就把自己潛在的運行崩潰這樣。

相關問題