create a protocol in swift

Creating a protocol in Swift is easy. You can define a protocol using the protocol keyword followed by the name of the protocol:

main.swift
protocol MyProtocol {
    func myMethod()
}
44 chars
4 lines

In this example, the MyProtocol protocol defines a single method called myMethod().

To conform to the MyProtocol protocol, a class or struct must implement the myMethod() method. This is done by adding the MyProtocol protocol to the class or struct declaration and implementing the required method:

main.swift
class MyClass: MyProtocol {
    func myMethod() {
        // implementation here
    }
}
89 chars
6 lines

In this example, MyClass conforms to the MyProtocol protocol and implements the myMethod() method.

Protocols in Swift can also inherit from other protocols using the : operator:

main.swift
protocol MySubProtocol: MyProtocol {
    func mySubMethod()
}
62 chars
4 lines

In this example, the MySubProtocol protocol inherits from the MyProtocol protocol and defines an additional method called mySubMethod().

To conform to the MySubProtocol protocol, a class or struct must implement both the myMethod() method from MyProtocol and the mySubMethod() method from MySubProtocol.

Using protocols can help improve your code reusability and modularity. By defining the interface in a protocol, you can make sure that multiple classes or structs conform to the same interface, which can make your code more flexible and easier to maintain.

gistlibby LogSnag