CODEX

Swift Protocols: How to Create Contracts in Your Code

Learn how to create code blueprints to write modular and decoupled Swift code

Artturi Jalli
CodeX
Published in
3 min readFeb 1, 2021

--

Protocols in Swift
Photo by Fotis Fotopoulos on Unsplash

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 and color contain { get set }. This means when a type conforms to Animal protocol, it must contain both name and color 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.

--

--

Artturi Jalli
CodeX

Check @jalliartturi on YouTube to become a successful blogger. (For collabs, reach me out at: artturi@bloggersgoto.com)