Binding template variables cannot appear in an expression

I am looking at the Swift Programming Language manual provided by apple. The following sample 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 wrote the closure incorrectly as follows:

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

Note the parentheses around let text = self.text and the compiler complains:

Binding template variables cannot appear in an expression

Just wondering what Pattern Variable Binding means and why it can't appear in an expression?

+6
source share
1 answer

Binding template variables is what you do, that is, using let in the middle of some code, and not at the top level of a file or enumeration or structure or class as a way of declaring a constant variable.

What makes this expression parenthesized. You cut the "let" expression from your environment and asked to evaluate it as an expression separately. But you cannot do this: you cannot say β€œlet” anywhere.

Another way to look at it is simple: if let is a fixed, meaningful template in which the condition is optional, which is evaluated to a constant for use inside if-code. The bracket broke the pattern.

A template is called a binding because you define this name very temporarily and locally, that is, exclusively in the if-code. I think it goes back to LISP (at least to where I used "let" in this way in the past).

+14
source

Source: https://habr.com/ru/post/970359/


All Articles