How Function Reference Works When a Function is Overloaded in Swift
This article assumes you understand how function reference, function signature and overloading work in Swift. If not, I would recommend that you begin by reading the following.
In a previous post, I provided two solutions to solving an ambiguous function reference. This piece is a continuation of that, but here I’m dealing with the problem of using a function reference when a function is overloaded.
Say you want to access an overloaded function, the full name solution will give you an error because the functions have the same full names. In such cases, you’ll need to implement the function signature solution.
Recommended by LinkedIn
Referencing an Overloaded Function
class Greeting{
func greet() {
}
func greet(_ hello: String) {
print("\(hello), Adam")
}
func greet(_ greeted: Bool) {
if greeted {
print("Welcome back!")
}
}
func sendGreeting() {
let userGreeting = greet(_:) // error: Ambiguous use of 'greet'
}
}
Here, the Greeting{. . .} class has three functions named greet, two of which are overloaded.
Using the function full-name greet(_:) produces an error of ambiguity. Swift doesn't know the function being referenced because both functions share the full name greet(_:).
class Greeting{
func greet() {
}
func greet(_ hello: String) {
print("\(hello), Adam")
}
func greet(_ greeted: Bool) {
if greeted {
print("Welcome back!")
}
}
func sendGreeting() {
let userGreeting = greet(_:) as (Bool) -> ()
}
}
To resolve this error, replace the function’s full name with the function’s signature.
Note: When referencing overloaded functions, you need to provide the function’s signature (type).