3

I'm learning with the book "Functional Swift", and there's a code snippet I don't understand.

indirect enum Tree <Element: Comparable> {
    case Leaf
    case Node(Tree <Element>, Element, Tree <Element>)
}

extension Tree {
    init() {
        self = .Leaf
    }
    init(_ value: Element) {
        self = .Node(.Leaf, value, .Leaf)
    }
    var isEmpty: Bool {
        if case .Leaf = self {
            return true
        }
        return false
    }
}

let a = Tree<Int>()
let b = Tree<Int>(5)

a.isEmpty
b.isEmpty

It 's if case .Leaf = self that confused me. Why case is not in the switch block, and why it uses assignment(=) rather than equation(==) in condition statement. I know it means if this enumeration value is .Leaf then blablabla, but the syntax I really don't understand.

Tepmnthar
  • 548
  • 3
  • 23
  • Compare [How case works in if-case](http://stackoverflow.com/q/37888376/2976878) – Hamish May 01 '17 at 09:29
  • It is just a syntactic sugar, another way to check the enum case. It is also possible to write `if self == .Leaf` – Toldy May 01 '17 at 09:29
  • Compare http://stackoverflow.com/a/33560859/1187415. – Martin R May 01 '17 at 09:31
  • 4
    @Toldy: No, there is no default `==` operator for enums with associated values. – Martin R May 01 '17 at 09:35
  • Compare http://stackoverflow.com/questions/30720289/swift-2-pattern-matching-in-if: *"if statements now support pattern matching like switch statements already have"* – Martin R May 01 '17 at 09:37
  • Worth noting that you can always refer to the [grammar section of the language guide](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AboutTheLanguageReference.html#//apple_ref/doc/uid/TP40014097-CH29-ID345) to see exactly how the syntax is derived. In this case you'll want to start at [`if-statement → if­ condition-list ­code-block ­else-clause­opt`](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Statements.html#//apple_ref/swift/grammar/branch-statement). – Hamish May 01 '17 at 09:38
  • @MartinR Oh yes, thanks for the precision. I forgot ! – Toldy May 02 '17 at 10:11

0 Answers0