使用闭包初始化Swift结构体

4
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
})
1个回答

7
构造函数传递的闭包会修改给定的参数,因此必须采用 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接