Reputation: 12581
I have a UInt16 variable that I would like to pass to a legacy function that requires an NSNumber.
If I try:
var castAsNSNumber : NSNumber = myUInt16
I get a compiler error 'UInt16' is not convertible to 'NSNumber'
How can I recast this as an NSNumber?
Upvotes: 15
Views: 18710
Reputation: 132869
Swift 4 or newer (still works in 5.5.1):
import Foundation
let u16 = UInt16(24)
let nsnum = u16 as NSNumber
let andBack = UInt16(truncating: nsnum)
print("\(u16), \(nsnum), \(andBack)")
Try yourself: https://swiftfiddle.com/bido2kr4x5fqnlptznxtbra76e
Or instead of
let andBack = UInt16(truncating: nsnum)
you can also use
let andBack = nsnum.uint16Value
Upvotes: 2