String to NSNumber in Swift

Solution 1:

Swift 3.0

NSNumber(integer:myInteger) has changed to NSNumber(value:myInteger)

let someString = "42222222222"
if let myInteger = Int(someString) {
    let myNumber = NSNumber(value:myInteger)
}

Swift 2.0

Use the Int() initialiser like this.

let someString = "42222222222"
if let myInteger = Int(someString) {
    let myNumber = NSNumber(integer:myInteger)
    print(myNumber)
} else {
    print("'\(someString)' did not convert to an Int")
}

This can be done in one line if you already know the string will convert perfectly or you just don't care.

let myNumber = Int("42222222222")!

Swift 1.0

Use the toInt() method.

let someString = "42222222222"
if let myInteger = someString.toInt() {
    let myNumber = NSNumber(integer:myInteger)
    println(myNumber)
} else {
    println("'\(someString)' did not convert to an Int")
}

Solution 2:

Or do it just in one line:

NSNumberFormatter().numberFromString("55")!.decimalValue

Solution 3:

In latest Swift:

let number = NumberFormatter().number(from: "1234")

Solution 4:

Swift 2

Try this:

var num = NSNumber(int: Int32("22")!)

Swift 3.x

 NSNumber(value: Int32("22")!)