Overcoming Default Arguments in a Protocol
Overcome the main Swift limitation for protocol
Protocol extensions to the rescue!
This article contains a real example for you that is used in production Apps. Don’t say I don’t spoil you (because I don’t).
Difficulty: Beginner | Easy | Normal | Challenging
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.
This is incredibly useful, and I’ve used just such a feature when I’ve created a Network Manager, and this gives a rather handy example for the rest of this article.
Now I want this to work with REST APIs, meaning I would want this to work for GET
, POST
, PUSH
, PUT
, DELETE
and PATCH
— but for some of these you might need to provide data in the body of the request. However for the GET
request we shouldn’t add any data.