swift 中的简短闭包形式,延迟加载
short form of closure in swift, lazy loading
我正在阅读 Strong reference cycle for closure
Apple 文档。下面是一个使用闭包的惰性变量声明:
lazy var asHTML: () -> String = {
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
下面是Swift
中闭包的语法
{(parameters) -> return type in
statements
}
它们看起来不一样,但我知道第一个 asHTML
是闭包的缩写形式
谁能告诉我如何推导出简短形式的原始语法
声明如下
() -> String
这意味着闭包不接受任何参数,并在调用时生成一个字符串。此闭包强烈捕获变量 self 以便能够使用文本。
如果我们采用闭包定义
{(parameters) -> return type in
statements
}
上面的asHTML可以改写为
{ () -> String in
statements
}
或
{ (Void) -> String in
statements
}
与
相同
lazy var asHTML = asHTML()
func asHTML() -> String {
....
}
作为附加说明,您还可以将惰性 asHTML 声明重写为
lazy var asHTML: String = {
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}()
Swift 允许您根据上下文省略部分闭包语法,以便于阅读。
在您的案例中,您将自动闭包分配给 asHTML 变量。
来自 Apple 关于自动闭包的文档
An autoclosure is a closure that is automatically created to wrap an
expression that’s being passed as an argument to a function. It
doesn’t take any arguments, and when it’s called, it returns the value
of the expression that’s wrapped inside of it. This syntactic
convenience lets you omit braces around a function’s parameter by
writing a normal expression instead of an explicit closure.
您可以阅读有关自动闭包和闭包语法的更多信息here。
我正在阅读 Strong reference cycle for closure
Apple 文档。下面是一个使用闭包的惰性变量声明:
lazy var asHTML: () -> String = {
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}
下面是Swift
中闭包的语法{(parameters) -> return type in
statements
}
它们看起来不一样,但我知道第一个 asHTML
是闭包的缩写形式
谁能告诉我如何推导出简短形式的原始语法
声明如下
() -> String
这意味着闭包不接受任何参数,并在调用时生成一个字符串。此闭包强烈捕获变量 self 以便能够使用文本。
如果我们采用闭包定义
{(parameters) -> return type in
statements
}
上面的asHTML可以改写为
{ () -> String in
statements
}
或
{ (Void) -> String in
statements
}
与
相同lazy var asHTML = asHTML()
func asHTML() -> String {
....
}
作为附加说明,您还可以将惰性 asHTML 声明重写为
lazy var asHTML: String = {
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}()
Swift 允许您根据上下文省略部分闭包语法,以便于阅读。
在您的案例中,您将自动闭包分配给 asHTML 变量。
来自 Apple 关于自动闭包的文档
An autoclosure is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it. This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.
您可以阅读有关自动闭包和闭包语法的更多信息here。