2015-06-26 29 views
3
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 
}) 

回答

4

传递给构造函数的封闭修改给定参数, 因此必须采取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 
+0

谢谢,似乎很详细,但它终于工作 –