How to automatically create an initializer for a Swift class?
Solution 1
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'
For older Xcode
There are handy plugins:
https://github.com/rjoudrey/swift-init-generator https://github.com/Bouke/SwiftInitializerGenerator
Solution 2
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
}
Solution 3
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.
Related videos on Youtube
Bhavuk Jain
StackExchange/Stackoverflow Security Hall of Fame: http://stackexchange.com/about/security Sr. iOS developer. Need some help or want a project to be done. Hit me up on my skype: bhavukjain.1
Updated on July 09, 2022Comments
-
Bhavuk Jain almost 2 years
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.-
David P about 6 yearsKinda bizarre this doesn't exist...
-
Bhavuk Jain about 6 years@Chicken You should use structs. They have so many benefits as compared to classes.
-
David P about 6 yearsI also need Objective-C compatibility.
-
Tomte about 4 yearsNow that some time went by, I'm facing another issue with this when using structs: If you have some default values assigned the internal initializer works well on Swift 5+. But on Swift 4 and below you have to add an initializer manually. So the accepted answer is gold. just quickly change from class to struct, do the refactor thingy, change it back to struct and no hassle. Note: Just for downwards compatibility necessary.
-
-
Paulo Mattos almost 7 years@BhavukJain If my answer solved your question, pls be sure to mark it as the accepted answer when you get a chance... thanks man!
-
Bhavuk Jain almost 7 yearsI'll upvote it because you mentioned something I didn't know. But still, I'm looking for an answer by how classes can achieve this. Maybe someone has created a tool for it so it can be used directly. There must be a way!
-
Paulo Mattos almost 7 years@BhavukJain The answer, circa Swift 3.1, is simply no, there isn't such feature for classes :( And peeking into the future it seems no such capability is in the roadmap either (this one was close but it was postponed). Of course, you could always use a code generator for this but it seems too much trouble if you ask me ;)
-
Christian Wolf Alves Hess over 5 yearsswiftinitializergenerator worked perfectly for me, thank you
-
Rudedog almost 5 yearsThis works well, but note that it only works for
class
declarations, notstruct
declarations. -
Daniel Wood almost 5 yearsUnfortunately this doesn't work if you want to make the struct accessible from another module as the memberwise initialisers are set to internal access and require you to recreate the memberwise initialiser by hand (or the tools listed above).
-
tyoc213 over 4 yearsWell, indeed doesnt work for structs, but you can change for a moment
struct
toclass
, generate the intializer and make it again astruct
;). -
Moris Kramer about 4 years@TangMonk
13.3.1
is an operating system. You mean Xcode 11.3, Yes only in 11.4 for structs and classes. Below that only for aclass. You can use plugins or rename struct to class temporly. -
TangMonk about 4 yearsI an using Version 11.3.1 (11C504) for Xcode, the 11.4 seems in beta
-
Justin about 4 yearsWhat a cool feature. It is really handy for adding initializers for view models. It helps to get rid of this boring task. Thanks for your hint.
-
Zorayr almost 4 yearsDo you know what could make the refactor options be blurred out? I right click on the class > Refactor > all options are blurred out 😢 my code compiles, I am on Xcode 11.4.
-
Burgler-dev over 3 yearsThis one saves me a lot off time, didn't know you had to click on the class/struct name first.
-
Aetherna about 3 yearsDoesn't work for me sadly. My xCode does "boop" sound and nothing happens..