6

I've been looking at The Swift Programming Language guide provided by apple. Following sample is from the book:

class HTMLElement {
    let name :String;
    let text: String?;

    @lazy var asHTML : () -> String = {
        if let text = self.text {
            return "<\(self.name)>\(self.text)</\(self.name)>";
        } else {
            return "<\(self.name) />"
        }
    }
}

I incorrectly wrote the closure as follow:

    @lazy var asHTML : () -> String = {
        if (let text = self.text) {
            return "<\(self.name)>\(self.text)</\(self.name)>";
        } else {
            return "<\(self.name) />"
        }
    }

Notice the parentheses around let text = self.text and compiler complain about:

Pattern variable binding cannot appear in an expression

Just wondering what does Pattern Variable Binding mean, and why it cannot appear in an expression?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Amir
  • 9,577
  • 11
  • 41
  • 58
  • Does it make sense to do sth like this in other languages? I dont thing so e.g `if( var name='CjCoax'){ console.log('you will notreach here') }`. Its javascript example but good to explain what you are trying to do – sakhunzai Jun 05 '14 at 03:33
  • @cjcoax several differences with objective-C and swift are demonstrated in your code: 1) ';' aren't needed, although the compiler safely ignores them. 2) Parens aren't needed (or in cases such as this, allowed in flow control statements – David Berry Jun 05 '14 at 06:03

1 Answers1

14

A "pattern variable binding" is the thing you're doing, i.e. using let in the middle of some code, not at the top level of a file or enum or struct or class as a way of declaring a constant variable.

What makes it an expression is the parentheses. You've cut the "let" expression off from its surroundings and asked for evaluation of it as an expression separately. But you can't do that: you can't say "let" just anywhere.

Another way of looking at it is simply this: if let is a fixed meaningful pattern, where the condition is an Optional being evaluated into a constant for use inside the if-code. The parenthesis broke up the pattern.

The pattern is called a binding because you're defining this name very temporarily and locally, i.e. solely down into the if-code. I think it goes back to LISP (at least, that's where I've used "let" this way in the past).

matt
  • 515,959
  • 87
  • 875
  • 1,141