How to cast from UInt16 to NSNumber
Asked Answered
C

2

15

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'

Question

How can I recast this as an NSNumber?

Compte answered 10/6, 2014 at 6:55 Comment(3)
How about var castAsNSNumber : NSNumber = NSNumber(myUInt16) ?Willi
Thanks Adam, although your suggestion didn't work, it triggered a compiler hint that produced the answer that John has posted.Compte
That is not casting, it is creating an NSNumber from a integer.Melatonin
L
38
var castAsNSNumber = NSNumber(unsignedShort: myUInt16)
Lascivious answered 10/6, 2014 at 7:6 Comment(1)
Swift 3: var castAsNSNumber = NSNumber(value: myUInt16)Berkley
B
2

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
Blueing answered 10/11, 2021 at 15:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.