以下沿着大书呆子牧场指南书我遇到了一个章节中的一段,要求您创建一个NumberFormatter
的实例。一切正常,但我注意到,格式化使用创建closure
为:NumberFormatter只能写在封闭
class ConversionViewController: UIViewController {
let numberFormatter: NumberFormatter = {
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}()
func updateCelsiusLabel() {
if let celsiusValue = celsiusValue {
celsiusLabel.text = numberFormatter.string(from: NSNumber(value: celsiusValue.value))
} else {
celsiusLabel.text = "???"
}
}
}
只是出于好奇,我试图像封闭的外创建此格式:
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
但得到的错误说
个预计声明
我的问题是:
- 为什么不能
NumberFormatters
封闭外面在这种情况下, 创建? - 括号
()
表示在 结束时表示什么?我的猜测是它是自我调用的,但为什么它需要成为?
到目前为止,我从来没有见过用这种方式写封闭。 Apple文档中是否有解释这一点的内容?
您可以在创建格式化程序的位置共享更多代码吗? –
可能的重复https://stackoverflow.com/questions/29835490/expected-declaration-error-using-swift/29835573#29835573 –
@Ahhhhhhhh我更新了我的问题。让我知道这是否足够。 –