WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

Improvements to synthesized memberwise initializers

Available from Swift 5.1

Paul Hudson      @twostraws

SE-0242 introduced major improvements to one of Swift’s most commonly used features: memberwise initializers for structs.

In earlier versions of Swift, a memberwise initializer was automatically created to accept parameters matching the properties of a struct, like this:

struct User {
    var name: String
    var loginCount: Int = 0
}

let piper = User(name: "Piper Chapman", loginCount: 0)

In Swift 5.1 this has been enhanced so that the memberwise initializer now uses default parameter values for any properties that have them. In the User struct we’ve given loginCount a default value of 0, which means we can either specify it or leave it to the memberwise initializer:

let gloria = User(name: "Gloria Mendoza", loginCount: 0)
let suzanne = User(name: "Suzanne Warren")

This lets us avoid repeating code, which is always welcome.

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Other changes in Swift 5.1…

Download all Swift 5.1 changes as a playground Link to Swift 5.1 changes

Browse changes in all Swift versions

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.