Being able to specify default parameter values in Swift allows us to reduce the number of function overloads in our code. For protocols it is still possible as long as we use an extension and delegate to the version without the default values.
protocol ErrorController {
func showError(_ error: String, delegate: ErrorViewControllerDelegate?)
}
extension ErrorController {
func showError(_ error: String, delegate: ErrorViewControllerDelegate? = nil) {
showError(error, delegate: delegate)
}
}
class ContactsViewController: UIViewController, ErrorController {
func showError(_ error: String, delegate: ErrorViewControllerDelegate?) {
print(error)
}
}
let contacts: ErrorController = ContactsViewController()
contacts.showError("I don't need a delegate.")
I hope the article was useful. If you have any feedback or questions please feel free to reach out.
Thanks for reading!
WRITTEN BY
Andrew Lord
A software developer and tech leader from the UK. Writing articles that focus on all aspects of Android and iOS development using Kotlin and Swift.
Want to read more?
Here are some other articles you may enjoy.