Reputation: 4820
struct User {
let name: String
let age: Int
}
Available member-wise initializer: User(name: String, age: Int)
struct User {
let name: String
let age = 1
}
Available member-wise initializer: User(name: String)
struct User {
let name: String
var age = 1
}
Available member-wise initializers:
User(name: String)
User(name: String, age: Int)
In case 2, there is no-way to set the value for property age
unless you create an instance of the struct as a variable.
Is this by design? Or is this a limitation in the member-wise initializer for Swift?
Upvotes: 0
Views: 72
Reputation: 299265
Yes, this is by design. age
is a constant here and can only be set one time. If you want a default value for a constant, you write an initializer.
struct User {
let name: String
let age: Int
init(name: String, age: Int = 1) {
self.name = name
self.age = age
}
}
Upvotes: 3