Sitemap

The Great Misunderstanding of Swift Protocol Extensions and Default Arguments

Common Mistake of Extending a Protocol with Default Arguments, How Dangerous It Is, and How to Fix It

4 min readMay 29, 2024

--

Recently, I’ve started noticing more and more people making the mistake of using default arguments in protocol extensions. Even relatively experienced fellow programmers often fall into this trap, and this is why I’m writing this seemingly simple blog post explaining some basic concepts of the Swift programming language.

Not a member? Read here for free.

The Problem and a Wrong Way to Fix It

As most of you, I’m sure, already know, Swift doesn’t allow default arguments to method parameters in protocols. The code below won’t compile:

protocol SomeProtocol {

// Default argument not permitted in a protocol method
func doSomething(with number: Int = 0)

}

How do we overcome this obstacle? Why, of course with the help of an extension! We can declare a method with the same name in the extension, but without parameters, and provide it with an implementation that calls the original protocol method with the default argument’s value:

protocol SomeProtocol {
func…

--

--

Nikita Lazarev-Zubov
Nikita Lazarev-Zubov

Written by Nikita Lazarev-Zubov

Swift and general programming topics, Agile software development, soft skills

No responses yet