简体   繁体   中英

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

Need help in following code.

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

--- Output

Failure
Success One

--- Expected Output

Success One Two
Success One

Demo: http://swiftstub.com/65065637

As far as I know, you are doing the casting wrong.

Here are the changes I have made to your code so that it works:

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

Output:

Success One Two
Success One

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM