2

can someone help me understand what's going on in the last line of this code snippet in Swift3?

    enum Movement {
        case Left
        case Right
        case Top
        case Bottom
    }

    let aMovement = Movement.Left

    // so I get all this so far ... then this:

    if case .Left = aMovement { print("move left") }

aMovement is already been defined, so I'm not sure what the single "=" is doing exactly. It seems like it should be an "==" to check a comparison - but that gives an error.

RichWalt
  • 502
  • 1
  • 4
  • 13
  • Related: [Swift 2 - Pattern matching in “if”](http://stackoverflow.com/questions/30720289/swift-2-pattern-matching-in-if), [How case works in if-case](http://stackoverflow.com/q/37888376/2976878), [What are the advantages/use cases of optional patterns introduced in swift 2?](http://stackoverflow.com/questions/36880109/what-are-the-advantages-use-cases-of-optional-patterns-introduced-in-swift-2) – Hamish Nov 25 '16 at 19:56

1 Answers1

2

From this reference:

The case let x = y pattern allows you to check if y does match the pattern x.

Writing if case let x = y { … } is strictly equivalent to writing switch y { case let x: … }: it’s just a more compact syntax which is useful when you only want to pattern-match against one case — as opposed to a switch which is more adapted to multiple cases matching.

Although it seems like the "==" should be used, with Pattern Matching in this case, it's not. (No pun intended)

dispatchswift
  • 1,046
  • 9
  • 21
  • Okay ... I see that now. The "case" keyword thrown in there as well as calling this a "switch pattern match" helps explain the single equals. It's seems like a quick doubt-check short cut the the full fledged switch statement (which must be exhaustive, when formally declared). thanks makes better sense, even as to when it would be helpful to use that syntax as opposed to the full switch statement ! thanks again – RichWalt Nov 28 '16 at 22:08