0

I am writing a framework in Objective-C, and the goal is it should be a joy to use in Swift as well.

One of my properties is a nullable NSNumber. Is there any way to bridge this to an optional Int when the API is used in Swift?

below
  • 929
  • 6
  • 26

1 Answers1

1

As per the documentation:

Swift automatically bridges certain native number types, such as Int and Float, to NSNumber.

It also allows you to pass a value of type Int, for example, to an argument expecting an NSNumber. Note that because NSNumber can contain a variety of different types, you cannot pass it to something expecting an Int value.

All of the following types are automatically bridged to NSNumber:

  • Int
  • UInt
  • Float
  • Double
  • Bool

So you can safely use these scalar types in swift and cast them to NSNumber in objc, but not the other way around. NSNumber may represent a float value, and you will see an error if you cast it to Int in swift.

Fujia
  • 1,232
  • 9
  • 14
  • Right, I was hoping there was a way to "promise" an Int NSNumber so that there would be a bridging … – below Jul 15 '16 at 10:37
  • You could you `NSInteger` which is automatically bridged to swift as `Int`. – Fujia Jul 15 '16 at 10:40
  • But I don't see the problem of using a NSNumber in Swift. Just calling integerValue will return its value converted to Int – crisisGriega Jul 15 '16 at 13:34