protocol in swift

In Swift, a protocol is a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. Protocols define a list of methods and properties that any conforming class, structure or enumeration must implement.

Declaring a protocol in Swift is straightforward. Here is an example:

main.swift
protocol Animal {
    var name: String { get set }
    func makeSound() -> String
}
84 chars
5 lines

This Animal protocol requires any conforming type to implement a name property of type String with both get and set accessors, and a makeSound() method that returns a String.

To conform to a protocol, you simply need to add the protocol name after the class, structure or enumeration name, separated by a colon. Here is an example:

main.swift
class Dog: Animal {
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func makeSound() -> String {
        return "Woof!"
    }
}
171 chars
12 lines

This Dog class conforms to the Animal protocol by implementing the required name property and makeSound() method.

Protocols can also be used in combination with delegates to enable communication between different parts of your code. You can use the protocol keyword to declare a delegate:

main.swift
protocol ExampleDelegate {
    func didReceiveData(data: Data)
}

class Example {
    var delegate: ExampleDelegate?
    
    func fetchData() {
        // ...
        delegate?.didReceiveData(data: someData)
    }
}
217 chars
13 lines

In this example, the Example class has a delegate property of type ExampleDelegate. The ExampleDelegate protocol requires any conforming type to implement the didReceiveData(data:) method. By calling the delegate?.didReceiveData(data:) method, the Example class can communicate with any object that conforms to the ExampleDelegate protocol.

Finally, Swift allows protocols to inherit from other protocols, and you can use extensions to add functionality to existing protocols. These features give you more power and flexibility to create reusable and composable code.

gistlibby LogSnag