代码之家  ›  专栏  ›  技术社区  ›  Carl Edwards monkbroc

NumberFormatter只能在闭包中写入

  •  0
  • Carl Edwards monkbroc  · 技术社区  · 7 年前

    大书呆子牧场指南 这本书我在其中一章中遇到了一段话,要求你创建一个 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
    

    但有一个错误是这样说的

    预期声明

    我的问题是:

    1. NumberFormatters 在该中的闭包外创建 案例
    2. () 在末尾表示

    到目前为止,我从未见过以这种方式编写闭包。苹果文档中有什么可以解释这一点吗?

    3 回复  |  直到 7 年前
        1
  •  1
  •   dfrib    7 年前

    这个 NumberFormatter 此外,闭包实例化在这里也是一个转移注意力的问题:问题是您试图更改实例属性( nf

    比较:

    struct Foo {
        var a = 1
        a = 2 // Error: expected declaration
    }
    

    编译示例如下:

    struct Foo {
        var a = 1
        mutating func mutateMe() {
            a = 2 // OK
        }
    }
    

    至于你的问题 2) () 用于执行闭包的一次性调用,其中闭包的返回用于实例化 nf .如果你没有调用它,那么 nf 将是类型的闭合 () -> 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
    
        2
  •  1
  •   Muzahid    7 年前

    第一个答案: 我在操场上测试了你的代码片段,它没有显示任何错误。我认为你可能做错了与 NumberFormatter

    let nf = NumberFormatter()
    nf.numberStyle = .decimal
    nf.minimumFractionDigits = 0
    nf.maximumFractionDigits = 1
    

    第二个答案: 闭包结束花括号告诉Swift立即执行闭包。如果省略这些括号,则试图将闭包本身分配给属性,而不是闭包的返回值。 App Doc

        3
  •  0
  •   Mohammad Sadiq    7 年前

    nf

    let nf = NumberFormatter()
    

    nf为您提供,但具有默认属性。并且不能在声明中设置其属性。您将收到此错误。

    enter image description here