Rahul Katariya
Rahul Katariya

Reputation: 3628

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

Upvotes: 4

Views: 65

Answers (1)

Sohel L.
Sohel L.

Reputation: 9540

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!

Upvotes: 4

Related Questions