How to automatically create an initializer for a Swift class?
Update As of Xcode 11.4
You can refactor
(right-click mouse menu) to have generated class and struct memeberwise initializer
.
Note: struct
auto inititializers are internal. You may what to generate memeberwise initializer
when you writing a module to make it public
.
Right-click > Refactor > 'Generate Memberwise Initialization'
For older Xcodes
There is a handy plugin for Xcode:https://github.com/rjoudrey/swift-init-generator or https://github.com/Bouke/SwiftInitializerGenerator
Thanks to plugins creators.
Given the following class (or for structs if temporarily change the keyword struct
to class
and after refactor set back to struct
):
class MyClass { let myIntProperty: Int let myStringProperty: String let myOptionalStringProperty: String? let myForcedUnwrappedOptionalStringProperty: String!}
Go to Xcode and:
- Double click the class name
- Right click
- Refactor
- Generate Member-wise Initializer
Above steps look like this:
Just a tiny second later, Xcode generates this initializer:
internal init(myIntProperty: Int, myStringProperty: String, myOptionalStringProperty: String?, myForcedUnwrappedOptionalStringProperty: String?) { self.myIntProperty = myIntProperty self.myStringProperty = myStringProperty self.myOptionalStringProperty = myOptionalStringProperty self.myForcedUnwrappedOptionalStringProperty = myForcedUnwrappedOptionalStringProperty}
No, there is no such feature for classes. But, if you design this as a struct
, you get an memberwise initializer for free — assuming you don't define others initializers yourself.
For instance:
struct Point { var x: Float var y: Float}...var p = Point(x: 1, y: 2)
From The Swift Programming Language book:
Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers. Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that do not have default values.
The memberwise initializer is a shorthand way to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name.