以下内容摘自:
As described above,optionals indicate that a constant or variable is allowed to have “no value”. Optionals can be checked with anif
statement 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.f2er.com/swift/327149.html