Convert optional string to int in Swift

I am having problems converting an optional string to int.

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

Result

  str_VAR = Optional(100) nil 

And I want it to be

  str_VAR = Optional(100) 100 
+7
swift optional
source share
3 answers

You can expand it as follows:

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

See IT for more details.

When to use if let?

if let is a special structure in Swift that allows you to check if Option has a value, and if it does, do something with the expanded value. Let's get a look:

 if let yourStr = str_VAR?.toInt() { println("str_VAR = \(yourStr)") println(yourStr) }else { //show an alert for something else } 

The if if structure flips str_VAR?.toInt() (i.e., checks to see if the value is stored and accepts that value) and stores its value in the constant yourStr . You can use yourStr inside the first if branch. Please note what is inside if you do not need to use? or! more. It is important to understand that yourStr has an Int type, which is not an optional type, so you can directly use its value.

+4
source share

Swift 3

At the time of writing, the other answers on this page use the pre-Swift 2 syntax. This is an update.

Convert Extra String to Int: String? -> Int String? -> Int

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

This converts the string "100" to an integer of 100 and prints the result. If optionalString were nil , hello or 3.5 , nothing was printed.

Also consider using guard statement .

+7
source share

Try the following:

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

All Articles