在Swift中将可选字符串转换为int

moo*_*der 9 optional swift

将可选字符串转换为int时遇到麻烦.

   println("str_VAR = \(str_VAR)")      
   println(str_VAR.toInt())
Run Code Online (Sandbox Code Playgroud)

结果是

   str_VAR = Optional(100)
   nil
Run Code Online (Sandbox Code Playgroud)

我想要它

   str_VAR = Optional(100)
   100
Run Code Online (Sandbox Code Playgroud)

Sur*_*gch 11

在撰写本文时,此页面上的其他答案使用了旧的Swift语法.这是一次更新.

将可选字符串转换为Int: String? -> Int

let optionalString: String? = "100"
if let string = optionalString, let myInt = Int(string){
     print("Int : \(myInt)")
}
Run Code Online (Sandbox Code Playgroud)

这会将字符串"100"转换为整数100并打印输出.如果optionalStringnil,hello或者3.5,什么都不打印.

还要考虑使用guard声明.


Dha*_*esh 6

你可以这样打开它:

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

}
Run Code Online (Sandbox Code Playgroud)

请参阅信息以获取更多信息.

何时使用"if let"?

if let是Swift中的一个特殊结构,它允许您检查一个Optional是否包含一个值,如果它存在,则使用unwrapped值执行某些操作.我们来看一下:

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

}else {
    //show an alert for something else
}
Run Code Online (Sandbox Code Playgroud)

if let结构展开str_VAR?.toInt()(即检查是否存储了值并获取该值)并将其值存储在yourStr常量中.你可以yourStr在if的第一个分支内使用.请注意,如果您不需要使用内部?要么 !了.重要的是要意识到yourStr实际上类型Int不是可选类型,因此您可以直接使用其值.