How to choose specific initializer when signatures are the same?

Viewed 59

I have an Item struct with 2 initializers:

  1. init(), which sets default values inside the body.
  2. init(isAvailable:count:), which has default arguments.
struct Item {
    var isAvailable: Bool
    var count: Int

    init() {
        self.isAvailable = false
        self.count = 0
    }

    init(isAvailable: Bool = true, count: Int = 100) {
        self.isAvailable = isAvailable
        self.count = count
    }
}

This compiles fine. However, when I do...

let item = Item()

... how do I control which init is actually used?

Since there are no parameters being passed in, both initializers should be possible candidates. The first one, init(), obviously matches. The init(isAvailable: Bool = true, count: Int = 100) {} should also be fine, since the default arguments let me skip passing them in.

Swift seems to use the first init() {}:

let item = Item()
print(item) /// Item(isAvailable: false, count: 0)

However, is there a way I can choose to use the second initializer instead?

let item = Item-2() /// Something like this.
print(item) /// Item(isAvailable: true, count: 100)

I could pass in one of the parameters, resolving the ambiguity, but then I'd need to keep track of the default value elsewhere. I'd prefer not to do this.

let item = Item(isAvailable: true) /// must remember the default value is `true`
print(item) /// Item(isAvailable: true, count: 100)

How do I choose which initializer to use when their signatures match?

0 Answers
Related