話不多說,直接上代碼
方式1:
var optional1: String?
var optianal2: String?
if let optional1 = optional1, optianal2 = optianal2 {
}
看起來很美~問題來了:如果我希望處理optional1有值,optional2沒值的情況怎么辦?聰明的你立馬想到了:
if let optional1 = optional1 {
guard let _ = optianal2 else{
print(optional1)
return
}
}
那optional1無值,optional2有值的情況,optional1與optional2都沒值的情況吶...別打我:)
可見,方法一在遇到需要對多個可選值分開判斷有無值的時候,似乎變得十分無力。可見的一個實際應用場景是登錄界面:假設我們有loginNameTextField
與passwordTextField
兩個輸入框,當用戶點擊登錄按鈕時,我們需要對兩個輸入框進行是否有值的判斷,進而給用戶拋出對應的錯誤。
那有沒有其他的方式來解包多個可選值?我們來看看第二種方式看是否可以優雅地解決這個問題。
方式2:
//Swift2
var username: String?
var password: String?
switch (username, password) {
case let (username?, password?):
print("Success!")
case let (username?, nil):
print("Password is needed!")
case let (nil, password?):
print("Username is needed!")
case (nil, nil):
print("Password and username are needed!")
}
看起來好多了~等等,case let (username?, nil):
中的?
是什么鬼,無需驚恐,這里的?
跟可選值的?
沒有一點關系。username?
表示的是username
有值, nil
即表示無值。事實上,這個?
是Swift2新增的語法,我們來看看Swift2以前是怎樣的:
//Before Swift2
var username: String?
var password: String?
switch (username, password) {
case let (.Some(username), .Some(password)):
print("Success!")
case let (.Some(username), .None):
print("Password is needed!")
case let (.None, .Some(password)):
print("Username is needed!")
case (.None, .None):
print("Password and username are needed!")
}
相比較而言,新的語法看起來精簡了許多。