objective-cswifttypesbridging

Annotate NSArray<NSNumber *> * in Objective-C so that it is bridged to Array<Int>


Is there a way to annotate an NSArray of NSNumber:

@property (nonatomic) NSArray<NSNumber *> *myProperty

in Objective-C, so that it will be imported in Swift as

var myProperty: [Int] instead of var myProperty: [NSNumber]?

I know of NS_SWIFT_NAME, but that does not allow changing the type.


Solution

  • Unfortunately you can't change the static type when importing a symbol from Objective-C.

    But you can assign a Swift Int array without any type cast (assuming foo is an instance of the ObjC class). However the type doesn't change.

    foo.myProperty = [1, 2, 3, 4, 5]
    print(type(of: foo.myProperty)) // Optional<Array<NSNumber>>
    

    On the other hand to get a distinct [Int] type you have to cast the type

    let mySwiftProperty = foo.myProperty as! [Int]
    print(type(of: mySwiftProperty)) // Array<Int>