Pattern matching (any, any) as (string, string) does not work in case of switch

Need help with the 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")
}

--- Exit

Failure
Success One

--- Expected Result

Success One Two
Success One

Demo: http://swiftstub.com/65065637

+4
source share
1 answer

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

Here are the changes I made to your code to make it work:

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!

+4
source

Source: https://habr.com/ru/post/1623194/


All Articles