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 an if 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 will always have 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 as implicitly 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."



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值