Swift Tour 隨筆總結 (3),swifttour

來源:互聯網
上載者:User

Swift Tour 隨筆總結 (3),swifttour

關於Optional的Control Flow

if let constantName = someOptional {

    statements

}

如果該Optional為nil,則不進入if,否則執行且constantName為該Optional的值

例子:

if let actualNumber = possibleNumber.toInt() {

    println(“\(possibleNumber) has an integer value of \(actualNumber)”)

} else {

    println(“\(possibleNumber) could not be converted to an integer”)

}

// prints “123 has an integer value of 123”

關於nil

optional可以被賦值為nil

例如:

var serverResponseCode: Int? = 404

serverResponseCode = nil

 

var surveyAnswer: String?

// surveyAnswer is automatically set to nil

 

optional的拓展:Implicitly Unwrapped Optionals

有的時候,一個optional在第一次賦值之後將是安全的,不用做nil檢查

定義:String! 而不是 String?

舉例:

let possibleString: String? = “An optional string.”

println(possibleString!) //  requires an exclamation mark to access this value

// prints “An optional string.”

 

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

println(assumedString) // no exclamation mark is needed to access its value

// prints “An implicitly unwrapped optional string.”

 

對於這種特殊類型(IUO),適用普通optional用法:

if assumedString {

println(assumedString)

}

 

Assertions – debugging中發現問題後的中斷

let age = –3

assert(age >= 0, “A person’s age cannot be less than zero”)

// assertion trigger

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.