Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically create an initializer for a Swift class?

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.

like image 225
Bhavuk Jain Avatar asked Apr 06 '17 12:04

Bhavuk Jain


People also ask

How do you initialize a class object in Swift?

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 ... } }

What is default initializer in Swift?

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.

What does init () do in Swift?

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.

How do you initialize a structure in Swift?

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.


1 Answers

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'

xcode 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.

like image 59
Moris Kramer Avatar answered Oct 12 '22 23:10

Moris Kramer