PassKit
PassKit

Reputation: 12581

How to cast from UInt16 to NSNumber

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?

Upvotes: 15

Views: 18710

Answers (2)

Mecki
Mecki

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

John Estropia
John Estropia

Reputation: 17500

var castAsNSNumber = NSNumber(unsignedShort: myUInt16)

Upvotes: 38

Related Questions