如何在 Swift 中展开可选 while 模式匹配?
How to unwrapping an optional while pattern matching in Swift?
有两个 UIAlertView
变量,但只有一个是可选的。比方说
lazy var a: UIAlertView = {
return UIAlertView() // Which is not important here
}()
var b: UIAlertView?
和委托方法
func alertView(alertView: SPAlertView!, clickedButtonAtIndex buttonIndex: Int) {
switch (alertView, buttonIndex) {
case (a, 0): // Do something
case (a, 1): // Do something
case (b, 1): // <== Want to do something here but, b is optional.
default: break
}
}
如何在模式匹配时展开 b
?
注意:问题是关于 Swift language
而不是关于 UIAlertView
。
有什么帮助吗?
您可以使用 where 子句来检查 alertView 是否等于 b
。
case (_, 1) where alertView == b:
为了确保 alertView
展开不是零,只需将下划线替换为 .some
。
case (.Some, 1) where alertView == b:
或者类似地,您可以让展开的 alertView,但这与上面的基本相同。
case (let .Some(_alertView), 1) where _alertView == b:
你可以试试这个(在案例中使用 ?
)
您需要将 self.b 添加到要打开的元组:
func alertView(alertView: SPAlertView!, clickedButtonAtIndex buttonIndex: Int) {
switch (b, alertView, buttonIndex) {
case (_, a, 0), (_,a,1): // Do something
case (b?, a, 1): // <== b is not optional here (only matches case .Some = b and binds to local variable `b`
default: break
}
}
有两个 UIAlertView
变量,但只有一个是可选的。比方说
lazy var a: UIAlertView = {
return UIAlertView() // Which is not important here
}()
var b: UIAlertView?
和委托方法
func alertView(alertView: SPAlertView!, clickedButtonAtIndex buttonIndex: Int) {
switch (alertView, buttonIndex) {
case (a, 0): // Do something
case (a, 1): // Do something
case (b, 1): // <== Want to do something here but, b is optional.
default: break
}
}
如何在模式匹配时展开 b
?
注意:问题是关于 Swift language
而不是关于 UIAlertView
。
有什么帮助吗?
您可以使用 where 子句来检查 alertView 是否等于 b
。
case (_, 1) where alertView == b:
为了确保 alertView
展开不是零,只需将下划线替换为 .some
。
case (.Some, 1) where alertView == b:
或者类似地,您可以让展开的 alertView,但这与上面的基本相同。
case (let .Some(_alertView), 1) where _alertView == b:
你可以试试这个(在案例中使用 ?
)
您需要将 self.b 添加到要打开的元组:
func alertView(alertView: SPAlertView!, clickedButtonAtIndex buttonIndex: Int) {
switch (b, alertView, buttonIndex) {
case (_, a, 0), (_,a,1): // Do something
case (b?, a, 1): // <== b is not optional here (only matches case .Some = b and binds to local variable `b`
default: break
}
}