tonytran tonytran - 5 months ago 31
iOS Question

short form of closure in swift, lazy loading

Im reading

Strong reference cycle for closure
from Apple docs. Below is a declaration of a lazy var using closure:

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


Below is a syntax of closure in Swift

{(parameters) -> return type in
statements
}


They dont look the same but I know that the first
asHTML
is a short form of closure

Can someone walk me through how I derive a short form form original syntax

Answer

The declaration reads

() -> String

Which means that the closure takes no arguments, and produces a String when called. This closure strongly captures the variable self to be able to use text.

If we take the closure definition

{(parameters) -> return type in
     statements
}

The above asHTML can be rewritten as

{ () -> String in
    statements
}

Or

{ (Void) -> String in
    statements
}

Which is the same as

lazy var asHTML = asHTML()

func asHTML() -> String {
    ....
}

As an additional note, you can also rewrite the lazy asHTML declaration as

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