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 error @ declaration of variable

cannot find initializer type 'style' accepts argument list of type '((_) -> _)' 

does know why won't work, seems legit code me

for record won't work either

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

the closure passed constructor modifies given argument, therefore must take inout-parameter , called &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 using self (as in build(&self)) requires properties have been initialized. works here because optionals implicitly initialized nil. alternatively define property non-optional initial value:

public var test : int = 0 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -