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?

Dan Beaulieu
  • 19,406
  • 19
  • 101
  • 135
PassKit
  • 12,231
  • 5
  • 57
  • 75

2 Answers2

38
var castAsNSNumber = NSNumber(unsignedShort: myUInt16)
John Estropia
  • 17,460
  • 4
  • 46
  • 50
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
Mecki
  • 125,244
  • 33
  • 244
  • 253