Swift initializes struct with 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 when declaring a variable

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

      

Does anyone know why this won't work seems to me to be legitimate code

for the record this won't work

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

      

+3


source to share


1 answer


The closure passed to the constructor modifies the given argument, so it must take an inout parameter and be called with &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 usage self

(as in build(&self)

) requires all of its properties to be initialized. This works here because options are implicitly initialized to nil

. Alternatively, you can define the property as optional with an initial value:

public var test : Int = 0

      

+4


source







All Articles