John Difool
John Difool

Reputation: 5702

Optional and default values need to be initialized with default initializer

Why can't I just bypass the initialization of b and c in the code below:

struct Token {
    var a: Int
    var b: Int = -1
    var c: Int?
}

let t1 = Token(a: 1, b: 2, c: 0) // works of course
let t2 = Token(a: 1) // doesn't work :-(

The only way I found is to add an init in the struct with the only mandatory parameter:

init(a: Int) { self.a = a }

But I find this language requirement very cumbersome and too verbose. Is there a way to achieve initialization of mandatory fields only without adding a constructor?

Upvotes: 2

Views: 3800

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59506

You can define an initializer with default values for some params

struct Token {
    var a: Int
    var b: Int
    var c: Int?

    init(a: Int, b: Int = -1, c: Int? = nil) {
        self.a = a
        self.b = b
        self.c = c
    }
}

Now you can create a Token in several ways

Token(a: 1) // (1, -1, nil)
Token(a: 1, b: 2) // (1, 2, nil)
Token(a: 1, c: 3) // (1, -1, 3)
Token(a: 1, b: 2, c: 3) // (1, 2, 3)

Usually is a good practice writing the default value of a property on the same line where it is defined (as you did). I moved the default value of b from it's definition to the init just to make this example shorter.

Upvotes: 4

Related Questions