Syntactic sugar for init properties in Swift?
class Person {
var name: String
var age: Int
func init(age: Int, name: String, /** ... **/) {
self.age = age
self.name = name
// ... much typing, much boring.
}
}
I may be a little lazy, but explicitly typing each property is very similar to a human compiler at work. Is there any syntactic sugar for assigning a constructor argument to an instance in Swift?
+3
source to share
1 answer
Check out the "Default Initializers" section of the Swift book. If you have to make a Person
struct instead of a class, it will automatically receive an initializer in order:
struct Person {
var name: String
var age: Int
}
let p = Person(name: "Joe", age: 30)
Classes or structs that define default values ββfor all properties they store receive a default initializer:
class Person {
var name: String = ""
var age: Int = 0
}
var p = Person()
p.name = "Joe"
p.age = 30
These auto-generated initializers disappear if you declare any of your own initializers in the original type declaration, but you can add other initializers to the extension.
+5
source to share