GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Protocols

Protocols are effectively contracts in Swift: they define a set of methods and properties that a type must implement if it says it conforms to the protocol. This contract gives us the flexibility to use different types to solve the same problem – we don’t get whether a ThingA or a ThingB is being used, as long as they both conform to the Thing protocol.

As an example, an Employee protocol might look like this:

protocol Employee {
    var name: String { get set }
    var jobTitle: String { get set }
    func doWork()
}

There are three important things in there.

First, both the properties have { get set } after them. This means that conforming types must make them both gettable (readable) and settable (writeable), which in turn means if a type says it is compatible with the Employee protocol it must make those two properties variables rather than constants.

Second, doWork() has no code inside it. Protocols are contracts defining how something ought to be able to behave, and don’t provide implementations of those behaviors.

Third, that protocol isn’t a concrete type, which means we can’t create instances of it. But we can create classes and structs that conform to it, like this:

struct Executive: Employee {
    var name = "Steve Jobs"
    var jobTitle = "CEO"

    func doWork() {
        print("I'm strategizing!")
    }
}

struct Manager: Employee {
    var name = "Maurice Moss"
    var jobTitle = "Head of IT"

    func doWork() {
        print("I'm turning it off and on again.")
    }
}

Now that we have a protocol and two types that conform to it, we can try using it:

let staff: [any Employee] = [Executive(), Manager()]

for person in staff {
    person.doWork()
}

Each `Employee` calls its version of `doWork`, so “I’m strategizing!” and “I’m turning it off and on again” are printed.

Because both types conform to Employee – they implement the properties and methods of that protocol – we can create an employee array and use the objects inside that array without knowing what their actual type is.

Notice how we use [any Employee] rather than just [Employee] – this is Swift’s way of making it clear in our code that the actual data types inside the array could be anything at all, as long as it conforms to the Employee protocol.

Hacking with Swift is sponsored by Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. This Black Friday, unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a free crash course.

Save your spot

Sponsor Hacking with Swift and reach the world's largest Swift community!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.