[英]Swift initialize a struct with a closure
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
})
传递给构造函数的闭包修改了给定的参数,因此它必须使用inout参数并使用&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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.