Memberwise Initializers in Swift

What is a memberwise initializer?

Payal Kandlur
3 min readNov 15, 2022

A memberwise initializer is an initializer that is added by default to structs by the compiler and these do not define the custom initializers.

Let's consider this struct People, with two constant properties name as String and age as Int

Because People struct has no custom initializer, the compiler generates a default initializer (memberwise initializer).

What are Default values?

Now let's have a struct Item with two properties, totalItems as Int and price as Double.

The compiler uses these default values we provided in the init above.

Now we know the compiler generates a memberwise initializer for the Item struct. The options to create Item object increases now. Xcode gives us four possibilities to create the object.

We can pass no values to the initializer. This is possible because each property has a default value.

We can specify values for either of them and the other parameter would be given the default value we specified at the top.

Memberwise Initializers are not available

The compiler only generates a memberwise initializer for a struct if the type declaration doesn’t define a custom initializer.

The suggestion list does not include the memberwise initializer.

What can be done then?

Just add the custom initializer in an extension! This gives us the best of both.

Memberwise Initializer for Classes

The compiler only generates memberwise initializers for structs, but it is possible to create one for classes.

On turning the struct into a class you see this error jumping up on your screen.

Add the initializer and it works fine.

That's all! Drop your suggestions and questions if any!😊

--

--

Responses (1)