4
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
})
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Andy Jacobs
  • 15,187
  • 13
  • 60
  • 91

1 Answers1

7

The closure passed to the constructor modifies the given argument, therefore 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 using self (as in build(&self)) requires that all its properties have been initialized. This works here because optionals are implicitly initialized to nil. Alternatively you could define the property as a non-optional with an initial value:

public var test : Int = 0
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382