在Swift模式匹配元组时如何解包Optional? [英] How do I unwrap an Optional when pattern matching tuples in Swift?
本文介绍了在Swift模式匹配元组时如何解包Optional?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Swift中,如果让模式用于解包选项,则会有一个共同的:
In Swift, there's a common if let
pattern used to unwrap optionals:
if let value = optional {
print("value is now unwrapped: \(value)")
}
我目前正在进行这种模式匹配,但在切换情况下使用元组,其中两个参数都是可选项:
I'm currently doing this kind of pattern matching, but with tuples in a switch case, where both params are optionals:
//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)"
我有没有办法解开我的可选和模式匹配,只有它不是零?目前我的解决方法是:
Is there a way I can unwrap my optional and pattern match only if it's not nil? Currently my workaround is this:
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)
的快捷方式,所以这相当于
x?
is just a shortcut for .some(x)
, so this is equivalent to
case (1990...2015, let .some(unwrappedUrl)):
print("Current year is \(year), go to: \(unwrappedUrl)")
这篇关于在Swift模式匹配元组时如何解包Optional?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文