Swift學習筆記之-Implicitly unwrapped optionals

來源:互聯網
上載者:User

標籤:

Implicitly unwrapped optionals:

// an implicitly unwrapped optional variable

varmaybeString:String!maybeString=nilmaybeString="fish"

// methods invoked directly, failing at runtime// if the optional is nil

ifmaybeString.hasPrefix("f") {

println("maybeString starts with ‘f‘")

}else{

println("maybeString does not start with an ‘f‘")

}

Tips:

?Implicitly unwrapped optionals are useful in classes and structs where you won’t

have a property’s value available in the initializer, but will have a value later

before it is used.

?Remember, implicitly unwrapped optionals are still optionals – use with them with

care since they remove a bit of safety around nil values!

隱式解析可選

如上所述,可選暗示了常量或者變數可以“沒有值”。可選可以通過if語句來判斷是否有值,如果有值的話可以通過可選綁定來解析值。

有時候在程式架構中,第一次被賦值之後,可以確定一個可選總會有值。在這種情況下,每次都要判斷和解析可選值是非常低效的,因為可以確定它總會有值。

這種類型的可選被定義為隱式解析可選(implicitly unwrapped optionals)。把想要用作可選的類型的後面的問號(String?)改成驚嘆號(String!)來聲明一個隱式解析可選。

當可選被第一次賦值之後就可以確定之後一直有值的時候,隱式解析可選非常有用。隱式解析可選主要被用在 Swift 中類的構造過程中,請參考類執行個體之間的迴圈強引用。

一個隱式解析可選其實就是一個普通的可選,但是可以被當做非可選來使用,並不需要每次都使用解析來擷取可選值。下面的例子展示了可選String和隱式解析可選String之間的區別:

let possibleString: String? ="An optional string."

println(possibleString!)// 需要驚歎號來擷取值

// 輸出 "An optional string."

let assumedString: String! ="An implicitly unwrapped optional string."

println(assumedString)// 不需要驚嘆號

// 輸出 "An implicitly unwrapped optional string."

你可以把隱式解析可選當做一個可以自動解析的可選。你要做的只是聲明的時候把驚嘆號放到類型的結尾,而不是每次取值的可選名字的結尾。

注意:如果你在隱式解析可選沒有值的時候嘗試取值,會觸發執行階段錯誤。和你在沒有值的普通可選後面加一個驚歎號一樣。

你仍然可以把隱式解析可選當做普通可選來判斷它是否包含值:

if  assumedString {

   println(assumedString)

}

// 輸出 "An implicitly unwrapped optional string."

你也可以在可選綁定中使用隱式解析可選來檢查並解析它的值:

if let definiteString = assumedString {

println(definiteString)

}

// 輸出 "An implicitly unwrapped optional string."

注意:如果一個變數之後可能變成nil的話請不要使用隱式解析可選。如果你需要在變數的生命週期中判斷是否是nil的話,請使用普通可選類型。

Swift學習筆記之-Implicitly unwrapped optionals

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.