Member-only story

The Great Misunderstanding of Swift Protocol Extensions and Default Arguments

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

Nikita Lazarev-Zubov
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.

Wrong Way

So, what exactly is the mistake I’m talking about?

As most of you, I’m sure, already know, Swift doesn’t allow default arguments to method parameters in protocols. The code below doesn’t even 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 doSomething(with number: Int)
}…

--

--

Nikita Lazarev-Zubov
Nikita Lazarev-Zubov

Written by Nikita Lazarev-Zubov

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

No responses yet