【问题标题】:Swift initialize a struct with a closureSwift 用闭包初始化结构
【发布时间】:2015-06-26 10:51:08
【问题描述】:
public struct Style {

    public var test : Int?

    public init(_ build:(Style) -> Void) {
       build(self)
    }
}

var s = Style { value in
    value.test = 1
}

在声明变量时出错

Cannot find an initializer for type 'Style' that accepts an argument list of type '((_) -> _)'

有谁知道为什么这不起作用,对我来说似乎是合法代码

为了记录,这也行不通

var s = Style({ value in
    value.test = 1
})

【问题讨论】:

    标签: swift closures init


    【解决方案1】:

    传递给构造函数的闭包修改给定的参数, 因此它必须采用 inout-parameter 并使用 &self:

    调用
    public struct Style {
    
        public var test : Int?
    
        public init(_ build:(inout Style) -> Void) {
            build(&self)
        }
    }
    
    var s = Style { (inout value : Style) in
        value.test = 1
    }
    
    println(s.test) // Optional(1)
    

    请注意,使用self(如build(&self))要求其所有 属性已初始化。这在这里有效,因为可选 隐式初始化为nil。或者,您可以定义 具有初始值的非可选属性:

    public var test : Int = 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 2021-07-14
      相关资源
      最近更新 更多