Enr*_*tyo 6 pattern-matching optional ios swift
在Swift中,有一个if let用于解包选项的常见模式:
if let value = optional {
print("value is now unwrapped: \(value)")
}
Run Code Online (Sandbox Code Playgroud)
我目前正在进行这种模式匹配,但在切换情况下使用元组,其中两个参数都是可选项:
//url is optional here
switch (year, url) {
case (1990...2015, let unwrappedUrl):
print("Current year is \(year), go to: \(unwrappedUrl)")
}
Run Code Online (Sandbox Code Playgroud)
但是,这打印:
"Current year is 2000, go to Optional(www.google.com)"
Run Code Online (Sandbox Code Playgroud)
我有没有办法解开我的可选和模式匹配,只有它不是零?目前我的解决方法是:
switch (year, url) {
case (1990...2015, let unwrappedUrl) where unwrappedUrl != nil:
print("Current year is \(year), go to: \(unwrappedUrl!)")
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*n R 14
你可以使用这种x?模式:
case (1990...2015, let unwrappedUrl?):
print("Current year is \(year), go to: \(unwrappedUrl)")
Run Code Online (Sandbox Code Playgroud)
x?只是一个捷径.some(x),所以这相当于
case (1990...2015, let .some(unwrappedUrl)):
print("Current year is \(year), go to: \(unwrappedUrl)")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1074 次 |
| 最近记录: |