[SOLVED] How to automatically create an initializer for a Swift class?

Issue

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.

Solution

Update As of Xcode 11.4

You can refactor (right-click mouse menu) to generate the memberwise initializer for class and struct.

Note that struct automatic initializers are internal. You may want to generate memberwise initializer when defining a module to make it public.

Right-click > Refactor > ‘Generate Memberwise Initializer’

xcode generate memberwise initialization

For older Xcode

There are handy plugins:

https://github.com/rjoudrey/swift-init-generator https://github.com/Bouke/SwiftInitializerGenerator

Answered By – Moris Kramer

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *