Xcode Tip: How to Generate Memberwise Initializer for Classes
Memberwise initializer comes by default in Swift structs. It accepts values for all properties of the struct. However, this feature is missing for classes. The below code compiles fine, when User
is a struct:
struct User {
let firstName: String?
let lastName: String?
}
let user = User(firstName: "Vadim", lastName: "Bulavin")
However, it fails to compile for class:
class User { // Error: Class 'User' has no initializers
let firstName: String?
let lastName: String?
}
The solution is to generate memberwise initializer with built-in Xcode refactoring tool: Right click class name > Refactor > Generate Memberwise Initializer.
The generated code looks next:
class User {
internal init(firstName: String?, lastName: String?) {
self.firstName = firstName
self.lastName = lastName
}
let firstName: String?
let lastName: String?
}
Thanks for reading!
If you enjoyed this post, be sure to follow me on Twitter to keep up with the new content. There I write daily on iOS development, programming, and Swift.