[英]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
}
gives an error at the declaration of the variable 在声明变量时给出错误
Cannot find an initializer for type 'Style' that accepts an argument list of type '((_) -> _)'
Does anyone know why this won't work, it seems legit code to me 有谁知道为什么这不起作用,这对我来说似乎是合法的代码
for the record this won't work either 为了记录,这也无济于事
var s = Style({ value in
value.test = 1
})
The closure passed to the constructor modifies the given argument, therefore it must take an inout-parameter and be called with &self
: 传递给构造函数的闭包修改了给定的参数,因此它必须使用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)
Note that using self
(as in build(&self)
) requires that all its properties have been initialized. 请注意,使用
self
(如在build(&self)
)需要初始化其所有属性。 This works here because optionals are implicitly initialized to nil
. 这可以在这里工作,因为选项被隐式初始化为
nil
。 Alternatively you could define the property as a non-optional with an initial value: 或者,您可以将属性定义为具有初始值的非可选属性:
public var test : Int = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.