Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an NSString to an integer using Swift?

I need to convert an NSString to an integer in Swift: Here's the current code I'm using; it doesn't work:

 var variable = (NSString(data:data, encoding:NSUTF8StringEncoding))
 exampeStruct.otherVariable = (variable).intValue

Variable is a normal varable, and exampleStruct is a struct elsewhere in the code with a subvariable otherVariable.

I expect it to set exampleStruct.otherVariable to an int value of the NSString, but I get the following error:

"Cannot convert the expression's type () to type Float"

How do I convert an NSString to int in Swift?

like image 672
rocket101 Avatar asked Oct 30 '14 20:10

rocket101


People also ask

Can you convert string to Int Swift?

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 to convert string into integer in objective c?

6 int answer = [@"42" intValue]; 7 NSString *answerString = 8 [NSString stringWithFormat: @"%d", answer]; 9 NSNumber *boxedAnswer = 10 [NSNumber numberWithInt: answer]; 11 NSCAssert([answerString isEqualToString: 12 [boxedAnswer stringValue]], 13 @"Both strings should be the same");

How do you convert int to text in Swift?

To convert an Int value to a String value in Swift, use String(). String() accepts integer as argument and returns a String value created using the given integer value.


1 Answers

You have to unwrap 2 optionals there, notice that I have also declared variable as String adding ":String" there. Example:

if let variable:String = NSString(CString:"1", encoding: NSUTF8StringEncoding) {
    if let otherVariable = variable.toInt() {
        println(otherVariable) // "1"
    }
} 

In your case you should do like this:

if let variable:String = NSString(data: data, encoding: NSUTF8StringEncoding) {
    if let exampeStruct.otherVariable = variable.toInt() {
        println(exampeStruct.otherVariable) // "1"
    }
}
like image 113
Leo Dabus Avatar answered Oct 11 '22 14:10

Leo Dabus