在“大Nerd牧场指南”()中,我看到了一章中的一段,其中一章要求您创建一个NumberFormatter实例。一切正常工作,但我注意到格式化程序是使用closure创建的,如下所示:
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?()在闭包结尾处代表什么?我猜想这是自我调用,但为什么要这样呢?到目前为止,我从未见过以这种方式编写闭包。苹果的文档里有什么可以解释这一点的吗?
发布于 2017-08-03 13:04:14
NumberFormatter和闭包实例化在这里都是一个红鱼:问题是,您试图在类型声明的范围内直接更改实例属性(nf) (尽管您未能向我们展示您的所有代码确实都包含在类型定义的范围内),但是超出了例如实例函数或初始化器的范围。
与以下比较:
struct Foo {
var a = 1
a = 2 // Error: expected declaration
}一个编译示例是:
struct Foo {
var a = 1
mutating func mutateMe() {
a = 2 // OK
}
}至于问题2):parantheses ()用于只调用闭包一次,其中返回闭包用于实例化nf。如果您没有调用它,那么nf将是() -> NumberFormatter类型的闭包,而不是NumberFormatter的实际实例。与以下比较:
struct Foo {
let a: Int = {
var a = 1
a = 2
return a
}() // instantiate 'a' of Foo by _once-only
// invoking a specified closure_.
}与相同的概念相比,但在类型声明/定义之外:
// this is a closure
let aClosure: () -> Int = { _ in return 42 }
// this is an invokation of a closure
// (discarding the result)
_ = aClosure()
// this is also an invokation of a closure
let num = { _ in return 42 }() // 'num' inferred to Int发布于 2017-08-03 13:15:28
第一个答案:--我在游乐场测试您的代码片段,它不会显示任何错误。我认为你可能做了一些与NumberFormatter无关的错误。
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1的第二个答案:,封闭型的结束,卷曲大括号告诉斯威夫特立即执行关闭。如果省略这些括号,则尝试将闭包本身分配给属性,而不是将闭包的返回值分配给属性。App Doc
发布于 2017-08-03 13:14:59
在本例中,nf是一个实例属性。它本身就是一个拥有自己属性的类。当你宣布
let nf = NumberFormatter()nf支持您,但具有默认属性。您不能在声明中设置它的属性。你会得到这个错误。

https://stackoverflow.com/questions/45485014
复制相似问题