moonvader
moonvader

Reputation: 21091

Convert optional string to int in Swift

I am having troubles while converting optional string to int.

   println("str_VAR = \(str_VAR)")      
   println(str_VAR.toInt())

Result is

   str_VAR = Optional(100)
   nil

And i want it to be

   str_VAR = Optional(100)
   100

Upvotes: 13

Views: 26487

Answers (3)

Suragch
Suragch

Reputation: 511746

At the time of writing, the other answers on this page used old Swift syntax. This is an update.

Convert Optional String to Int: String? -> Int

let optionalString: String? = "100"
if let string = optionalString, let myInt = Int(string) {
     print("Int : \(myInt)")
}

This converts the string "100" into the integer 100 and prints the output. If optionalString were nil, hello, or 3.5, nothing would be printed.

Also consider using a guard statement.

Upvotes: 16

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

You can unwrap it this way:

if let yourStr = str_VAR?.toInt() {
    println("str_VAR = \(yourStr)")  //"str_VAR = 100" 
    println(yourStr)                 //"100"

}

Refer THIS for more info.

When to use “if let”?

if let is a special structure in Swift that allows you to check if an Optional holds a value, and in case it does – do something with the unwrapped value. Let’s have a look:

if let yourStr = str_VAR?.toInt() {
    println("str_VAR = \(yourStr)")
    println(yourStr)

}else {
    //show an alert for something else
}

The if let structure unwraps str_VAR?.toInt() (i.e. checks if there’s a value stored and takes that value) and stores its value in the yourStr constant. You can use yourStr inside the first branch of the if. Notice that inside the if you don’t need to use ? or ! anymore. It’s important to realise thatyourStr is actually of type Int that’s not an Optional type so you can use its value directly.

Upvotes: 6

Greg
Greg

Reputation: 25459

Try this:

if let i = str_VAR?.toInt() {
    println("\(i)")
}

Upvotes: 1

Related Questions