在Swift中将可选字符串转换为int [英] Convert optional string to int in Swift

查看:380
本文介绍了在Swift中将可选字符串转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having troubles while converting optional string to int.

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

结果是

   str_VAR = Optional(100)
   nil

我希望它成为

   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.

何时使用"if let"?

if let是Swift中的一种特殊结构,它使您可以检查Optional是否持有值,并在可能的情况下–对未包装的值进行处理.让我们看一下:

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
}

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

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.

这篇关于在Swift中将可选字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆