Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to NSNumber in Swift

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?

like image 246
user2413621 Avatar asked Feb 19 '15 11:02

user2413621


People also ask

What is NSNumber in Swift?

NSNumber is a subclass of NSValue that offers a value as any C scalar (numeric) type. It defines a set of methods specifically for setting and accessing the value as a signed or unsigned char , short int , int , long int , long long int , float , or double or as a BOOL .

How do I convert a string to int in Swiftui?

Using Int initializer Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.

How do I convert a string to a double in Swift?

To convert a string to a double, we can use the built-in Double() initializer syntax in Swift. The Double() initializer takes the string as an input and returns the double instance.


2 Answers

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") } 
like image 161
Wez Avatar answered Sep 27 '22 19:09

Wez


Or do it just in one line:

NSNumberFormatter().numberFromString("55")!.decimalValue 
like image 44
polarware Avatar answered Sep 27 '22 20:09

polarware