Improvements to synthesized memberwise initializers
About 2 min
Improvements to synthesized memberwise initializers 관련
HACKING WITH SWIFT
What's new in Swift?
Improvements to synthesized memberwise initializers | Changes in Swift 5.1
Improvements to synthesized memberwise initializers
Available from Swift 5.1
SE-0242 (apple/swift-evolution
) 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.
Other Changes in Swift 5.1
Implicit returns from single-expression functions | Changes in Swift 5.1
Implicit returns from single-expression functions
Universal Self | Changes in Swift 5.1
Universal Self
Opaque return types | Changes in Swift 5.1
Opaque return types
Static and class subscripts | Changes in Swift 5.1
Static and class subscripts
Warnings for ambiguous none cases | Changes in Swift 5.1
Warnings for ambiguous none cases
Matching optional enums against non-optionals | Changes in Swift 5.1
Matching optional enums against non-optionals
Ordered collection diffing | Changes in Swift 5.1
Ordered collection diffing
Creating uninitialized arrays | Changes in Swift 5.1
Creating uninitialized arrays