Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 模式无法匹配子类型的元组_Swift_Pattern Matching - Fatal编程技术网

Swift 模式无法匹配子类型的元组

Swift 模式无法匹配子类型的元组,swift,pattern-matching,Swift,Pattern Matching,考虑以下代码: protocol P {} struct A: P {} func match(_ l: P, _ r: P) { switch l { case is A: print("l is A") default: print("failed to match single value") } switch (l, r) { case is (A, A): print("(l, r) is (A, A)"

考虑以下代码:

protocol P {}

struct A: P {}


func match(_ l: P, _ r: P) {
  switch l {
    case is A:
      print("l is A")

    default:
      print("failed to match single value")
  }

  switch (l, r) {
    case is (A, A):
      print("(l, r) is (A, A)")

    case (_, _) as (A, A):
      print("(l, r) is (A, A)")

    default:
      print("failed to match tuple")
  }
}

match(A(), A())
在游乐场中运行此操作将生成以下输出:

l is A
failed to match tuple
显然,模式匹配子类型的元组不起作用。这是一个bug还是一个特性?如果是后者,了解原因会很有趣。

更新:在Swift 3.1中,Xcode 8.3 beta版可用,您的代码现在的行为与预期一致。)

这是一个bug,由跟踪。然而,根据该报告,该问题现在已在Swift存储库的主分支上得到解决,因此当Swift 3.1出现时(即“2017年春天”)一切都会好起来

但是,在此之前,一个简单的解决方案是单独检查元组中每个元素的类型:

switch (l, r) {
case (is A, is A):
    print("(l, r) is (A, A)")
default:
    print("failed to match tuple")
}
或者如果您需要在
案例中使用
l
r

switch (l, r) {
case let (l as A, r as A):
    print("(\(l), \(r)) is (A, A)")
default:
    print("failed to match tuple")
}
相关的: