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?
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.
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");
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.
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With