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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With