Search code examples
iosxcodeswiftnsstring

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?


Solution

  • edit/update:

    No need to use NSString when coding with Swift. You can use Swift native String(data:) initializer and then convert the string to Int:

    if let variable = String(data: data, encoding: .utf8),
        let integer = Int(variable) {
        exampeStruct.otherVariable = integer
    }
    

    If other variable is a Float type:

    if let variable = String(data: data, encoding: .utf8),
        let integer = Float(variable) {
        exampeStruct.otherVariable = integer
    }