[swift-users] Function overload resolution rules

Toni Suter tonisuter at me.com
Fri Sep 30 07:02:16 CDT 2016


Hi,

I am trying to get a better understanding of Swift's function overload resolution rules.
As far as I can tell, if there are multiple candidates for a function call, Swift favors
functions for which the least amount of parameters have been ignored / defaulted. For example:

// Example 1
func f(x: Int) {  print("f1") }
func f(x: Int, y: Int = 0) { print("f2") }
f(x: 0) 	// f1

// Example 2
func f(x: Int, y: Int = 0) {  print("f1") }
func f(x: Int, y: Int = 0, z: Int = 0) { print("f2") }
f(x: 0) 	// f1

It also looks like Swift favors functions with default-value parameters over functions with variadic parameters:

func f(x: Int = 0) {  print("f1") }
func f(x: Int...) { print("f2") }

f() 			// f1
f(x: 1) 		// f1
f(x: 1, 2) 		// f2 (makes sense because f1 would not work here)
f(x: 1, 2, 3) 		// f2 (makes sense because f1 would not work here)

But then I tested functions with default-value parameters and variadic parameters and things start to get weird.
For example, this must be a bug, right?

func f(x: Int..., y: Int = 0) { print(x, y) }
func f(x: Int...) { print(x) }

f()			// []
f(x: 1)			// [1]
f(x: 1, 2)		// [1, 2] 0
f(x: 1, 2, 3)		// [1, 2, 3]

I think, in this example, it should always call the second overload, because
no parameter is ignored / defaulted. What do you think?

Thanks and best regards,
Toni
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160930/6a97bed8/attachment.html>


More information about the swift-users mailing list