简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM