選配斯威夫特可以在第一混亂,但它有助於記住,他們只是一個枚舉,如:
enum Optional<T> {
case None
case Some(T) // swift enums can have data associated to them
}
如果您確定您的選購有非零值,即,它是一個.Some
,您可以通過感嘆號!
運算符來訪問此基礎值。
總之,力量解包optional!
說:「好吧,我確定這個可選包含非無值,給我。」
這就是所謂的強力展開。您正在告訴系統訪問對應於.Some(T)
的值,但您並未檢查您的可選項是否爲.Some
或.None
。如果你強制解開與!
和你的可選結果是.None
,你會得到運行時錯誤,你得到unexpectedly found nil while unwrapping an Optional value
。
作爲一個經驗法則,你應該總是檢查你的optionals之前解開它們。在少數情況下,您應該假設可選非零和強制展開它。例如,如果您嘗試在prepareForSegue
中訪問它,則即使是IBOutlet
也可能是nil
。 XCode自動使插座隱含地解開,因爲對於您的大多數視圖控制器的生命週期,它們不會是無。但你仍然必須照顧自己的這些不常見的邊緣情況,他們是無。
您可以檢查一個可選的具有非零值與
if optional != nil {
// force-unwrapping after nil check is fine
optional!.someMethod()
} else {
// 'optional' is nil
}
的標準方式更地道的方式與迅速做到這一點是通過可選結合。
// binds the constant 'value' to your optional if it is non-nil
if let value = optional {
value.someMethod()
} else {
// optional is nil
}
的第三種方式是檢查與後衛陳述。 守護語句的語義與前面的有所不同。您還可以混合使用警戒語句和可選綁定。
guard optional != nil else {
// optional is nil.
// by the end of this branch you must exit the block that
// encloses the guard statement, such as with a return or break
return
}
// if control reaches here you're guaranteed optional is non-nil
衛隊聲明都在迅速整齊的功能,因爲你可以專注於你想要的條件,而不是你不想要的東西。它還保留處理違反要求的代碼,以滿足相應的要求。與做相同的事情,如果發言,後衛通過使您的意圖明確提高可讀性。
要了解更多,請參閱swift documentation的基礎部分。
只是返回零。 Swift慣例是用小寫的第一個字母來命名你的方法 –