String to NSNumber in swift

user2413621 picture user2413621 · Feb 19, 2015 · Viewed 68.6k times · Source

I found a method to convert string to NSNumber, but the code is in objective-C. I have tried converting it to swift but it is not working.

The code i am using

NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:@"42222222222"];

and in swift i am using it in this way

var i = NSNumberFormatter.numberFromString("42")

But this code is not working, what am I doing wrong?

Thanks in advance

Answer

Wez picture Wez · Feb 19, 2015

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")
}