Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

uitableview - swift init not visible in objective-C

I'm trying to create init functions in Swift and create instances from Objective-C. The problem is that I don't see it in Project-Swift.h file and I'm not able to find the function while initializing. I have a function defined as below:

public init(userId: Int!) {
    self.init(style: UITableViewStyle.Plain)
    self.userId = userId
}

I even tried putting @objc(initWithUserId:) and I keep getting the same error again. Is there anything else I'm missing? How do I get the constructor visible to Objective-C code?

I read the below for this:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue you're seeing is that Swift can't bridge optional value types -- Int is a value type, so Int! can't be bridged. Optional reference types (i.e., any class) bridge correctly, since they can always be nil in Objective-C. Your two options are to make the parameter non-optional, in which case it would be bridged to ObjC as an int or NSInteger:

// Swift
public init(userId: Int) {
    self.init(style: UITableViewStyle.Plain)
    self.userId = userId
}

// ObjC
MyClass *instance = [[MyClass alloc] initWithUserId: 10];

Or use an optional NSNumber?, since that can be bridged as an optional value:

// Swift
public init(userId: NSNumber?) {
    self.init(style: UITableViewStyle.Plain)
    self.userId = userId?.integerValue
}

// ObjC
MyClass *instance = [[MyClass alloc] initWithUserId: @10];    // note the @-literal

Note, however, you're not actually treating the parameter like an optional - unless self.userId is also an optional you're setting yourself up for potential runtime crashes this way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...