DEV Community

Brittney Kernan
Brittney Kernan

Posted on

What is a memberwise initializer in Swift?

This is a heuristic I, a front-end developer learning SwiftUI, used to mentally map this intimidating term.

Mapping each word:

  • Initializer: A function that initializes an instance of an object, in this case, a structure, a.k.a. struct
  • Member: Members is another term for the properties of the struct
  • Wise: Knowledgable about the struct members/properties and capable of generating code

Putting it together:

A memberwise initializer is an initializer function that the Swift compiler conveniently auto-generates for you when you define a struct. This saves you the mundane task of writing an initializer function for structs.

A visual:

A screenshot of the struct code below with Xcode's code completion popup
See the suggested completion for the Song struct. It shows you the memberwise initializer’s function signature. Notice I did not type out an init function.

Try it yourself:

struct Song {
    let bpm: Int
    let artist: String
}
let greatestHit = Song( // code completion pops up here
Enter fullscreen mode Exit fullscreen mode

I encourage you to build a deeper understanding of the term by reading Bart Jacobs' article on memberwise initializers and following along with his code examples in XCode’s Playground. It’s also always a good idea to read the official Apple documentation, for now on memberwise initializers, for the freshest information, as Swift is updated about twice yearly.

Thanks for your time. Let me know if you have questions or suggested improvements to this post.

Top comments (0)