4

In the A.swift file I have

class A {
    func c(d: String = "abc") {
        // (1)
    }
}

and in the B.swift file I have

class B {
   func z() {
      let aaa = A()
      aaa.c()
   }
}

extension A {
    func c(d: String = "abc", e: String = "123") {
        // (2)
    }
}

Now, I'd like to know: in z()is called (1) or (2)? And how is it decided?

Hamish
  • 78,605
  • 19
  • 187
  • 280
Giorgio
  • 1,973
  • 4
  • 36
  • 51
  • 1
    did you try yourself? – mfaani Mar 30 '17 at 14:28
  • Yes! It's called (1) but I don't understand why – Giorgio Mar 30 '17 at 14:29
  • See [What is the difference between static func and class func in Swift?](http://stackoverflow.com/a/25157453/5175709) and its other answers. What you're asking is mostly about static vs dynamic dispatch, you can search for more related questions using "static dispatch [swift]" – mfaani Mar 30 '17 at 14:46
  • 3
    @Honey this question has nothing to do with dispatch, this is about function argument overloading – taylor swift Mar 30 '17 at 15:34
  • @taylorswift you're right. I'll just leave it there, so your comment won't be meaningless... – mfaani Mar 30 '17 at 17:30

1 Answers1

4

Your class A has two functions, c(d:), and c(d:e:). In Swift, two functions can share the same “first name”, but be distinguished by their arguments. Hence, the “full name” of a function consists of its name and all of its parameter labels.

Replace the line

aaa.c()

with

aaa.c(d:e:)()

which calls the function c(d:e:) by its full name, and (2) will execute.

Note that aaa.c() is equivalent to aaa.c(d:)(). Swift appears to default to the function with the fewest parameters when the call is ambiguous; this may be the subject of a future Swift Evolution proposal, if it is not already.

taylor swift
  • 2,039
  • 1
  • 15
  • 29
  • Thank you! I also think Swift calls the function with the fewest parameters when the call is ambiguous. Do you know if this is documented anywhere? – Giorgio Mar 30 '17 at 15:53
  • hah! so is this an overload or just a different function or basically overload translates into a different function? (I'm just trying to get the jargon right) – mfaani Mar 30 '17 at 17:29
  • @Honey technically it’s a different function with a different name but for people coming from languages where the function name is “the stuff that comes before the parentheses” it’s easier to think of them as overloads, especially when it comes to initializers. Swift’s disambiguation syntax kind of sucks which contributes to the confusion. – taylor swift Mar 30 '17 at 17:37