swift init not visible in objective-C

前端 未结 2 1349
灰色年华
灰色年华 2020-12-11 15:16

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 Proj

相关标签:
2条回答
  • 2020-12-11 15:45

    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.

    0 讨论(0)
  • 2020-12-11 15:48

    use this one:

    var index: NSInteger!
    
    @objc convenience init(index: NSInteger) {
        self.init()
    
        self.index = index
    }
    
    0 讨论(0)
提交回复
热议问题