在Swift中,有一个通用的if let模式可以用来解开可选项:
if let
if let value = optional { print("value is now unwrapped: \(value)") }
我目前正在执行这种模式匹配,但是在切换情况下使用元组,其中两个参数都是可选的:
//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?模式:
x?
case (1990...2015, let unwrappedUrl?): print("Current year is \(year), go to: \(unwrappedUrl)")
x?只是的快捷方式.some(x),因此等效于
.some(x)
case (1990...2015, let .some(unwrappedUrl)): print("Current year is \(year), go to: \(unwrappedUrl)")