UPDATE: Use structs and not classes. Struct is better in many ways has got an initializer of its own.
This is my model class. Is it possible to create the init
method automatically? Everytime I have to initialize all the variables one by one and it costs a lot of time.
class Profile { var id: String var name: String var image: String init(id: String, name: String, image: String) { self.id = id self.name = name self.image = image } }
I want self.id = id
and other variables to initialize automatically.
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }
Default Initializers. Swift provides a default initializer for any structure or class that provides default values for all of its properties and doesn't provide at least one initializer itself. The default initializer simply creates a new instance with all of its properties set to their default values.
Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.
In Swift, all structs come with a default initializer. This is called the memberwise initializer. A memberwise initializer assigns each property in the structure to self. This means you do not need to write an implementation for an initializer in your structure.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With