模式匹配 (Any, Any) as (String, String) 在 Switch Case 中失败

Pattern Matching (Any, Any) as (String, String) Fails in Switch Case

在以下代码方面需要帮助。

let first: Any = "One"
let second: Any = "Two"
let values = (first, second)

switch values {
case let (x, y) as (String, String):
    print("Success", x, y)
default:
    print("Failure")
}

switch first {
case let x as String:
   print("Success", x)
default:
   print("Failure")
}

--- 输出

Failure
Success One

--- 预期输出

Success One Two
Success One

演示:http://swiftstub.com/65065637

据我所知,您的转换有误。

以下是我对您的代码所做的更改,以使其正常工作:

let first: Any = "One"
let second: Any = "Two"
let values = (first, second)

switch values {
case let (x as String, y as String):
    print("Success", x, y)
default:
    print("Failure")
}

switch first {
case let x as String:
    print("Success", x)
default:
    print("Failure")
}

输出:

Success One Two
Success One

希望对您有所帮助!