How to use a protocol inside a function in Swift?

Viewed 250

I'm going through a series of Swift tutorials and I don't want to move forward without understanding the point of this

protocol Identifiable {
    var id: String { get set }
}
/*:
 We can’t create instances of that protocol - it’s a description, not a type by itself.
 But we can create a struct that conforms to it:
 */
struct User: Identifiable {
    var id: String
}
//: Finally, we’ll write a `displayID()` function that accepts any `Identifiable` object:
func displayID(thing: Identifiable) {
    print("My ID is \(thing.id)")
}

This is the tutorial page

Say I want to now run displayID and get the thing.id, how would that work?

3 Answers

You can try it on swift playgrounds this is one way you can use it for example:

import Foundation

protocol Identifiable {
    var id: String { get set }
}

struct User: Identifiable {
    var id: String
}

class ViewController {
    func displayID(thing: Identifiable) {
        print("My ID is \(thing.id)")
    }
}

let vc = ViewController()
let user = User(id: "12")
vc.displayID(thing: user)
// My ID is 12

Usually protocols are seen like contracts (interfaces in java/android) for a class or struct to follow, so you know that making a class or a struct comforming to a protocol will assure you an implementation of your basic methods that you might require for that kind of object/instance in future.

As well they are meant to allow you to provide in your automated tests for example a mocked sample of the implementation in order to get a mock id instead of a real one as in this example.

A protocol simply means ...

you MUST have all the stuff stated!

That is all a protocol is!

Here's your protocol

protocol Identifiable {
    var id: String { get set }
}

all that means is you MUST have a "id" !

So this:

class Test: Identifiable {
}

is wrong !!!

But this:

class Test: Identifiable {
   var id: String
}

is correct !!!

That's all it is!

Protocols are that simple!

Yes, it is true you cannot create an instance of protocol. But you can create an instance of classes and struct that implements protocol. Protocol just ensure that the struct or class that implements this protocol must have all these properties and methods that are defined in the protocol. You can say that Protocol is a contract. You need to fulfill it if you implements it.

Related