1

I recently found an Int initializer:

init?<S>(_ text: S, radix: Int = 10) where S: StringProtocol

As you can see, the second parameter radix has a default value with 10, so I can call this function without providing it.

Meanwhile, String does conform to this StringProtocol through the following extension:

extension String : StringProtocol { 
    //... 
}

And there is another initializer for Int:

init?(_ description: String)

Given the code:

let x = Int("123")

How could the Swift compiler know which initializer to call as this statement matches both of them. What factors influence its decision-making process?

HangarRash
  • 7,314
  • 5
  • 5
  • 32
Evan
  • 430
  • 6
  • 16
  • What difference would it make? In the absence of a radix the answer is 123 either way. – matt Jul 10 '23 at 07:43
  • type-checking time consumption may differ.@matt check this https://stackoverflow.com/questions/57302881/swift-type-check-takes-long-time – Evan Jul 10 '23 at 07:47
  • 1
    There is a lot of things that it considers. I think this might be too broad. In your specific case, it's because "leaving out optional parameters" is better than "*not* leaving out optional parameters". – Sweeper Jul 10 '23 at 07:47
  • So Swift is open source. Why not look at the code and see? – matt Jul 10 '23 at 07:52
  • You‘re right. I shouldn't try the easy way. – Evan Jul 10 '23 at 07:59
  • If you write it as `let x = Int.init("123")` then you can use Xcode's “jump to definition” feature to see which method is invoked, compare https://stackoverflow.com/q/32048978/1187415 – Martin R Jul 10 '23 at 08:11

0 Answers0