CODEX
Swift Protocols: How to Create Contracts in Your Code
Learn how to create code blueprints to write modular and decoupled Swift code
Published in
3 min readFeb 1, 2021
Swift Protocols
Swift protocols are a fundamental concept. A protocol is like a code contract. If a type conforms to a protocol, it must implement and include the variables and methods defined in the protocol.
Using protocols in Swift makes it possible to write more modular and decoupled code.
Example of Using Protocols in Swift
As an example, let’s create an Animal
protocol:
protocol Animal {
var name: String { get set }
var color: String { get set }
func makeSound()
}
Let’s inspect the Animal
protocol in a bit more detail before moving on:
- Variables
name
andcolor
contain{ get set }
. This means when a type conforms toAnimal
protocol, it must contain bothname
andcolor
variables that can be read and modified. - The
makeSound
method does not have an implementation. This is because a protocol does not care about the implementation of its methods. It only cares that the method is implemented in the type conforming to the protocol.