Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a protocol inside a function in Swift? [closed]

Tags:

swift

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?

like image 947
relidon Avatar asked Dec 05 '25 05:12

relidon


1 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.

like image 133
denis_lor Avatar answered Dec 07 '25 20:12

denis_lor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!