Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/43255522/how-to-automatically-create-an-initializer-for-a-swift-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...