Swift method defaults and params

In the file A.swift

I have

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

      

and in the file B.swift

I have

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

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

      

Now I would like to know: z()

is (1) or (2) being called? And how is it done?

+3


source to share


1 answer


There A

are two functions in your class : c(d:)

and c(d:e:)

. In Swift, two functions can share the same "name" but differ in their arguments. Therefore, the "fully qualified name" of a function consists of its name and all of its parameter labels.

Replace string

aaa.c()

      

from



aaa.c(d:e:)()

      

which calls the function c(d:e:)

by its fully qualified name, and (2)

will execute.

Please note that is aaa.c()

equivalent aaa.c(d:)()

. Swift seems to work with the smallest parameters by default when the call is ambiguous; it could be the subject of a future Swift Evolution if it isn't already there.

+1


source







All Articles