好文記錄與分享 軟體開發隨筆

Swift (3): about Optional

商業,創業,業務,職涯,美食,葡萄酒,閱讀,網路科技。

從 Larry 創業以及商業的經驗,希望以白話的口吻,介紹給大家這個商業的世界。

FB粉專會頻繁地更新 Larry 對於商業、社會、人生的觀察與心得,歡迎大家追蹤互動~

Marin Todorov's article: Swift Optionals: When to use if let, when ? and !, when as? and as
http://www.touch-code-magazine.com/swift-optionals-use-let/

The “class?property” Syntax

controller.navigationController?.pushViewController(myViewController, animated: true)

如果 controller.navigationController 不為 nil, 執行 function. 如果 controller.navigationController 為 nil, 整行程式碼不執行。他可以替換成:

if controller.navigationController != nil {
    controller.navigationController.pushViewController(myViewController, animated: true)
}


The “if let” Syntax

if let nav = controller.navigationController {
    nav.pushViewController(myViewController, animated: true)
} else {
    //show an alert ot something else
}

“if let” 的語法隱含了 “and if nav != nil”. 當你有多行程式碼需要 unwrap, use “if let”.

The “as?” Syntax

let myVC = controller.presentedViewController as? MyViewController
myVC?.lastUpdated = NSDate()

“as?” 有點像 C++ 的 dynamic cast, 以上面例子來說,myVC 有可能是 nil. 正因如此,”as?” 底下通常要接 “class?property”. 另外如果用 “as” 而不是 “as?” (沒有問號),則是 C++ 的 static cast,上面文章連結也有提到你要 101% 確定可以 cast 才用 “as” 去 cast.

商業,創業,業務,職涯,美食,葡萄酒,閱讀,網路科技。

從 Larry 創業以及商業的經驗,希望以白話的口吻,介紹給大家這個商業的世界。

FB粉專會頻繁地更新 Larry 對於商業、社會、人生的觀察與心得,歡迎大家追蹤互動~

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *