Convert optional string to int in Swift

安稳与你 提交于 2019-12-22 04:09:56

问题


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

回答1:


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.




回答2:


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.




回答3:


Try this:

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


来源:https://stackoverflow.com/questions/31694635/convert-optional-string-to-int-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!