Optional Value

晓晨
晓晨
Aug 24, 2017 · 1 min read

对于一个 optional value,

var i: Int?

或者 implicitly unwrapped optionals,

var i: Int!

都可以做下面这些操作

if let i = i ...

i?.intMethod

if i == nil ...或者 if i != nil ...

但是对于 if i == 5

如果 i 是普通 optional value 类型不匹配,无法通过编译,如果 i 是 IUO,则编译通过,在 i 为 nil 时会出现运行时错误。

关于 Implicitly Unwrapped Optionals

compromise between safety and convenience

Sometimes it is clear from a program’s structure that an optional will always have a value, after the 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. — The Swift Programming Language

it may be obvious that an optional will always have a value when you write the code … but code changes and assumptions change. — https://cocoacasts.com/when-should-you-use-implicitly-unwrapped-optionals/

尤其在他人修改代码时,可能做出不符合这个假设的改动。

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade