0

enter image description here

I am not sure how this works. As you can see there are two suggestions with the same name and argument type.

How it is decided which method is called?

It's the method with an argument which is called, but what if what I wanted to be called is the init which contains the calculations (without providing a value for the windSpeedMilesPerHour parameter)?

Bogdan Pop
  • 318
  • 1
  • 3
  • 12

1 Answers1

1

A quick test, stripped of all the dross from your example, tells you the answer:

struct S {
    init(a:Int) {
        print("first one")
    }
    init(a:Int, b:Int=3) {
        print("second one")
    }
}
let s = S(a:4) // "first one"

So basically the first initializer has made it impossible to call the second initializer without an explicit b parameter. That's a silly thing to do — you've made the default value for b useless and pointless — but it isn't illegal and there's no reason why it should be.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Yes, I know that the first one is called (as I said in the question). But is there a more in depth explanation? Why isn't the init with the b parameter called instead of the one without – Bogdan Pop Mar 20 '17 at 04:08
  • 2
    I don't understand the sense of the word "why" in that question, beyond what I've already said: it's because you've overshadowed the second initializer called with just one parameter with the first initializer. Swift has a heuristic for deciding what your code means and that's it. It's a very silly edge case, but it doesn't crash and the compiler doesn't slap you down, so go ahead and do it if you want to. If "why" means "what's happening behind the scenes", plow thru the source and figure it out; Swift is open source. Personally I prefer to treat it as a black box. – matt Mar 20 '17 at 04:11