12

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
moonvader
  • 19,761
  • 18
  • 67
  • 116

3 Answers3

16

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.

Andres Canella
  • 3,706
  • 1
  • 35
  • 47
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 1
    do you know why this construct results in nil? let optionalString: String? = "100" , let newVal = Int(optionalString!) – bibscy Mar 12 '18 at 14:04
6

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.

Community
  • 1
  • 1
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
1

Try this:

if let i = str_VAR?.toInt() {
    println("\(i)")
}
Greg
  • 25,317
  • 6
  • 53
  • 62