在 Swift 中,有一个常见的 if let
模式用于解包可选值:
if let value = optional {
print("value is now unwrapped: \(value)")
}
我目前正在做这种模式匹配,但是在 switch case 中使用元组,其中两个参数都是可选的:
//url is optional here
switch (year, url) {
case (1990...2015, let unwrappedUrl):
print("Current year is \(year), go to: \(unwrappedUrl)")
}
然而,这打印:
"Current year is 2000, go to Optional(www.google.com)"
有没有一种方法可以解包我的可选和模式匹配,只有当它不是零时?目前我的解决方法是:
switch (year, url) {
case (1990...2015, let unwrappedUrl) where unwrappedUrl != nil:
print("Current year is \(year), go to: \(unwrappedUrl!)")
}
最佳答案
您可以使用 x?
模式:
case (1990...2015, let unwrappedUrl?):
print("Current year is \(year), go to: \(unwrappedUrl)")
x?
只是 .some(x)
的快捷方式,所以这等同于
case (1990...2015, let .some(unwrappedUrl)):
print("Current year is \(year), go to: \(unwrappedUrl)")
关于ios - 在 Swift 中对元组进行模式匹配时如何解包 Optional?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37452118/