Overcoming Default Arguments in a Protocol

Overcome the main Swift limitation for protocol

Image for post
Image for post
Photo by Sebastian Herrmann on Unsplash

Prerequisites:

  • Be able to produce a “Hello, World!” iOS application (guide HERE)
  • Use of extensions in Swift (guide HERE)
  • Use of protocols in Swift (Guide HERE)

Terminology

Extensions: Extensions add new functionality to a class, struct, enum or protocol

The issue

When you use a function, or initialise a class you might well use default arguments.

func fetch(url: URL, method: HTTPMethod, headers: [String : String], token: String? = nil, data: [String: Any]?, completionBlock: @escaping (Result<Data, Error>) -> Void)

Conclusion

Due to the way Swift works you can’t add default arguments in a protocol method. This makes quite a few issues, in that we often do want to use a default argument even when we are conforming to a protocol. But there is a way that comes to the result:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store