加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift Optionals & Implicitly Unwrapped Optionals

发布时间:2020-12-14 02:12:25 所属栏目:百科 来源:网络整理
导读:以下内容摘自: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309 As described above,optionals indicate that a constant or variable is a

以下内容摘自:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309

As described above,optionals indicate that a constant or variable is allowed to have “no value”. Optionals can be checked with anifstatement to see if a value exists,and can be conditionally unwrapped with optional binding to access the optional’s value if it does exist.

// optional 指明一个常量或变量可以没有值。可以通过if 语句来查看值是否存在,如果值存在的话可以通过额外的optinal binding来获取到这个值。用?来定义

Sometimes it is clear from a program’s structure that an optional willalwayshave a value,after that value is first set. In these cases,it is useful to remove the need to check and unwrap the optional’s value every time it is accessed,because it can be safely assumed to have a value all of the time.

// 有时在程序的结构中当这个值被先设置后,这个optinal总是明确有一个值。这种情况下就不需要每次再去检查,取值了,因为有值的话就是安全的。

// implicitly unwrapped optional 用!来定义

These kinds of optionals are defined asimplicitly unwrapped optionals. You write an implicitly unwrapped optional by placing an exclamation mark (String!) rather than a question mark (String?) after the type that you want to make optional.

// implicitly unwrapped optional 最原始的使用是在类的初始化中 =等下回来update=

// 来看下这两者使用的区别

// 直接将implicitly unwrapped optional看作是 给了optional权限 每次使用自动获取到数据

<span style="color:#414141;">let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation mark
 
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // </span><span style="color:#ff0000;">no need for an exclamation mark</span>

// 要是这个implicitly unwrapped optional没有值的话,直接去获取的话就会出错 -?你妈 什么鬼 什么情况会出现 都确认一定有值了

// 那么这个implicitly unwrapped optional存在的意义是什么呢??????

// 我目前看到的都是@IBOutlet中的UILable啊什么的是加了! ->>如果你在有些地方,不希望它没有值,你就给他设置!,这样就能很快fail和crash

// 你可以将implicitly unwrapped optional看作是正常的optional

if assumedString != nil {
println(assumedString)
}
// prints "An implicitly unwrapped optional string."


// 你可以可以使用optional binding,来检查和获取它的值

if let definiteString = assumedString {
println(definiteString)
}
// prints "An implicitly unwrapped optional string."

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读