微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift Optionals & Implicitly Unwrapped Optionals

以下内容摘自:

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."

原文地址:https://www.jb51.cc/swift/327149.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐