Andy Jacobs
Andy Jacobs

Reputation: 15245

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
})

Upvotes: 4

Views: 2295

Answers (1)

Martin R
Martin R

Reputation: 540105

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

Upvotes: 8

Related Questions