Swift Protocols

Swift protocols are a way of defining a blueprint of methods, properties, and other requirements. In Swift, a class, structure, or enumeration can adopt a protocol to conform to its requirements.

Swift Defining a Protocol

A protocol is defined using the protocol keyword, followed by the name of the protocol, and a set of requirements.

1protocol MyProtocol { 2 func myFunction() 3 var myProperty: Int { get set } 4}

This defines a protocol called MyProtocol that has a single function requirement, and a read-write property requirement.

Swift Conforming to a Protocol

A class, structure, or enumeration can conform to a protocol by adopting it using the : operator.

1class MyClass: MyProtocol { 2 func myFunction() { 3 print("Hello, world!") 4 } 5 6 var myProperty: Int = 0 7}

In this example, MyClass conforms to the MyProtocol protocol by implementing its function and property requirements.

Swift Conforming to Multiple Protocols

A class, structure, or enumeration can conform to multiple protocols by separating them with commas.

1class MyOtherClass: MyProtocol, AnotherProtocol { 2 func myFunction() { 3 print("Hello, world!") 4 } 5 6 var myProperty: Int = 0 7 8 func anotherFunction() { 9 print("Another function!") 10 } 11 12 var anotherProperty: String = "" 13}

Swift Protocol Inheritance

Protocols can inherit from other protocols, just like classes can inherit from other classes.

1protocol AnotherProtocol: MyProtocol { 2 func anotherFunction() 3 var anotherProperty: String { get set } 4}

In this example, the AnotherProtocol protocol inherits from the MyProtocol protocol, and adds its own function and property requirements.

Swift Protocol Extensions

Protocol extensions provide a way to add default implementations for protocol requirements. Any type that conforms to the protocol automatically gets the default implementation.

1protocol MyProtocol { 2 func myFunction() 3 var myProperty: Int { get set } 4} 5 6extension MyProtocol { 7 func myFunction() { 8 print("Default implementation!") 9 } 10}

In this example, the MyProtocol protocol is extended with a default implementation of the myFunction() requirement. Any type that conforms to the MyProtocol protocol will get this default implementation, unless it provides its own implementation.