p0lAris
p0lAris

Reputation: 4820

Swift member wise initializer doesn't include parameters with default constant properties

Case 1

struct User {
  let name: String
  let age: Int
}

Available member-wise initializer: User(name: String, age: Int)

Case 2

struct User {
  let name: String
  let age = 1
}

Available member-wise initializer: User(name: String)

Case 3

struct User {
  let name: String
  var age = 1
}

Available member-wise initializers:

Issue

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

Answers (1)

Rob Napier
Rob Napier

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

Related Questions