如何在Swift模式匹配元组时解开一个Optional?

在Swift中,有一个常用的用于解开option的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? 模式:

 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)") 

你可以这样做:

 switch(year, x) { case (1990...2015,.Some): print("Current year is \(year), go to: \(x!)") } 

你也可以做

  switch(year, x) { case (1990...2015, let .Some(unwrappedUrl)): print("Current year is \(year), go to: \(unwrappedUrl)") }