7

I have a variable called number of type Int

var number = value!.integerValue as Int

Now I have to create a NSNumber object using that value.

I am trying to use this constructor

value = NSNumber(int: number)

, but it does not work.

It expect the primitive type int, not Int I guess.

Anyone know how to get around this?

Thanks!

Dima
  • 23,484
  • 6
  • 56
  • 83
ppalancica
  • 4,236
  • 4
  • 27
  • 42

3 Answers3

7

You just do value = number

As you can see in the documentation:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html

the native swift number types generally bridge directly to NSNumber.

Numbers

Swift automatically bridges certain native number types, such as Int and Float, to NSNumber. This bridging lets you create an NSNumber from one of these types:

SWIFT

let n = 42
let m: NSNumber = n
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

Swift 3 update

In Swift 3, this bridging conversion is no longer automatic and you have to cast it explicitly like this:

let n = 42
let m: NSNumber = n as NSNumber
Dima
  • 23,484
  • 6
  • 56
  • 83
  • On Ubuntu Linux, with Swift 3.0.2, this bridging doesn't occur. The prior two lines of code give `error: repl.swift:3:19: error: cannot convert value of type 'Int' to specified type 'NSNumber'` – Chris Prince May 07 '17 at 05:32
  • @ChrisPrince In Swift 3 this bridging is no longer automatic. You have to cast to an `NSNumber` by adding `as NSNumber` in the assignment. Adding it to my answer. – Dima May 07 '17 at 17:37
  • Hmmm. I think there is a difference in Foundation on MacOS and Linux in this regard. Also see http://stackoverflow.com/questions/43828307/numeric-types-dont-automatically-bridge-to-nsnumber-in-pure-swift-on-ubuntu-lin – Chris Prince May 08 '17 at 01:14
  • `NSNumber(value:1)` – Gal Jul 27 '17 at 13:33
4

The issue is because in ObjC, an int is a 32 bit number, and an integer or NSInteger is a 64 bit number.

var number = value!.integerValue as Int

Number is of type Int which corresponds to the ObjC type NSInteger

You now try to create with this:

value = NSNumber(int: number)

Which takes an Int32 or int type, thus resulting in failure. You have a few options that will work.

One:

value = NSNumber(int: Int32(number))

Two (probably better):

value = NSNumber(integer: number)

Three (probably best):

As @Dima points out, you can just set it directly because swift automatically converts:

value = number
Logan
  • 52,262
  • 20
  • 99
  • 128
4

For Swift 3 you must use:

var convertedNumber = NSNumber(value: numberToConvert)
Boris
  • 11,373
  • 2
  • 33
  • 35