Can a Swift Optional Int (Int?) be exposed to Objective-C via bridging?

后端 未结 2 709
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 12:13

Within a Swift class derived from an Obj-C based framework (but could just as easily be a Swift class with an @objc attribute) I declare two stored properties:



        
相关标签:
2条回答
  • 2020-12-01 12:22

    The problem with exposing an Int? property as NSNumber* is that you could store a non-Int-compatible NSNumber to it from Objective-C.

    You can make a computed NSNumber? property to wrap your Int? property. The getter would simply return the Int? variable. The setter would set the Int variable from -[NSNumber integerValue].

    0 讨论(0)
  • 2020-12-01 12:31

    Here's a concrete answer for the solution described above:

    private var _number: Int?
    public var number: NSNumber? {
        get {
            return _number as NSNumber?
        }
        set(newNumber) {
            _number = newNumber?.intValue
        }
    }
    
    // In case you want to set the number in the init
    public init(number: NSNumber?) {
        _number = number?.intValue
    }
    
    0 讨论(0)
提交回复
热议问题