Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result due to order in Swift's pattern matching

Sorry for the "Shouldn't this work?" question. But I can't figure out a better way to phrase this.

enum MyEnum {
    case A, B, C
}

let tuple = (MyEnum.C, MyEnum.A)    
var x: String

switch tuple {
case (.A, _):
    x = "(A, something)"
case (_, .A):
    x = "(something, A)"
case (_, .B):
    x = "(something, B)"
case (.C, .C):
    x = "(C, C)"
default:
    x = "default"
}

x // -> "default"

x evaluates to "default", which means the default branch was taken.

However, I was expecting "(something, A)" and the second case statement to match. From what I understood (_, .A) should match anything in the first tuple element, and .A in the second.

If I move the (_, .A) case to the top, it is matched as I expect it. Other tuples also match where I expect them to.

What am I missing? Why isn't this matched by the second case?

like image 941
nschum Avatar asked Jun 11 '14 18:06

nschum


1 Answers

This behavior has been corrected in beta 3. It now shows (Something, A) whatever the order is.

like image 86
Zaphod Avatar answered Nov 15 '22 11:11

Zaphod