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
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
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.
At the time of writing, the other answers on this page used old Swift syntax. This is an update.
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.
Try this:
if let i = str_VAR?.toInt() {
println("\(i)")
}