Skip to main content

Articles, snippets and thoughts about code from Andrew Lord.

Protocol functions with default parameter values

Published on · Updated on
1 minute read

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 to me on Twitter.

Thanks for reading and happy coding!

Like what you read? Please share the article.

Avatar of Andrew Lord

Hi, I hope you enjoyed the article. I am Andrew - a builder of apps and developer tools. Articles on the blog focus on all aspects of Android and iOS development using Kotlin and Swift.

Subscribe via RSS