在Swift模式匹配元组时如何解包Optional?

时间:2016-05-26 05:14:56

标签: ios swift pattern-matching optional

在Swift中,有一个常见的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!)")
}       

3 个答案:

答案 0 :(得分:12)

您可以使用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)")

答案 1 :(得分:1)

使用开关盒,您可以打开(在需要时)并在同一情况下评估未包装的值(通过使用where)。

像这样:

let a: Bool? = nil
let b: Bool? = true

switch (a, b) {
case let (unwrappedA?, unwrappedB?) where unwrappedA || unwrappedB:
  print ("A and B are not nil, either A or B is true")
case let (unwrappedA?, nil) where unwrappedA:
  print ("A is True, B is nil")
case let (nil, unwrappedB?) where unwrappedB:
  print ("A is nil, B is True")
default:
  print("default case")
}

答案 2 :(得分:0)

你可以这样做:

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