Swift

Protocols

Defining methods and properties for types

What is a protocol?

A protocol is a contract. It defines a set of methods/properties that a type must use to conform to the contract. We can now have flexibility in solving our problem. Let’s create a protocol for a family.

protocol FamilyMember {
    var name: String { get set }
    var age: String { get set }
    func hobbies()
}

What does this mean?

First, we have two properties: name and age. The “get set” means that we should be able to read and write to them, meaning that compatible properties must be variables rather than constants. At the end we have a hobbies function. This is empty. Like we said, protocols are contracts that define how something works without saying what it does. This is not a type, but a set of rules for a type to follow, like a struct. Let's create some of those.

struct Dad: FamilyMember {
    var name = "Frank Heffley"
    var age = 45
    func hobbies() {
        print("Civil War battlefield fanatic")
    }
}
    
struct OlderBrother: FamilyMember {
    var name = "Rodrick Heffley"
    var age = 16
    func hobbies() {
        print("Loded Diper Rock Star")
    }
}

Let’s put it to work

Now, let’s put these protocols and types to work.

let family: [FamilyMember] = [Dad(), OlderBrother()]

for member in family {
    person.hobbies()
}

Since both of these types follow the FamilyMember protocol, they use the same properties and methods of the protocols. We created a family array and used the protocol as guidance without knowing the real type.

chevron_up