Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a default memberwise initializer for a class in Swift?

Let’s say I have a class Foo:

class Foo {
   let bar: String
   let baz: String
}

Do I really have to write the memberwise initializer by hand?

init(bar: String, baz: String) {
    self.bar = bar
    self.baz = baz
}

It’s pure boilerplate.

like image 259
zoul Avatar asked Oct 12 '15 09:10

zoul


1 Answers

If you can work with value semantics instead of reference semantics, you can use a Struct instead of a Class, they have automatic memberwise initializers.

enter image description here

If not, then you have to provide the full init yourself for your class.

like image 100
Eric Aya Avatar answered Nov 15 '22 01:11

Eric Aya