create a protocol and use him in swift

To create a protocol in Swift, you can define it with the protocol keyword followed by the name of the protocol. Inside the curly braces, you can define the methods or properties that you want conforming classes or structs to implement.

Here's an example protocol named MyProtocol with one required method named myMethod:

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

To use this MyProtocol in a class or struct, you need to implement the required methods by conforming to the protocol. Here's an example class MyClass that adopts the MyProtocol:

main.swift
class MyClass: MyProtocol {
    func myMethod() {
        // do something
    }
}
82 chars
6 lines

You can also use the protocol as a type to create a variable or constant that can hold any object that conforms to the protocol. For example:

main.swift
let myObject: MyProtocol = MyClass()
myObject.myMethod()
57 chars
3 lines

In this example, myObject is of type MyProtocol, but it's actually an instance of MyClass which conforms to MyProtocol. Therefore, we can call the myMethod() method on myObject, which will call the implementation of the method in MyClass.

gistlibby LogSnag