Swift Introduction | Protocols and Extensions | Protocols
Swift programs process objects by calling their methods. When handling an object, you need to know which methods it provides.
Suppose several unrelated classes need to be processed together. It is useful if all of them provide a common method. When classes do not share an inheritance relationship, however, a superclass cannot guarantee that common method.
A protocol solves this problem. A protocol resembles a class that contains only property and method declarations.
protocol ProtocolName {
... property and method declarations ...
}
A method declaration does not need an implementation body. The protocol specifies only the required method signature.
A class adopts a protocol with syntax similar to inheritance.
class ClassName : ProtocolName {...}
When a class also inherits from a superclass, write the superclass first and separate protocols with commas. A class can adopt multiple protocols.
A class that adopts a protocol must implement every requirement in that protocol. Otherwise, compilation fails. This guarantees that all conforming classes provide the required methods.
The following example defines and uses a protocol.
protocol MyProtocol {
func printData ()
}
class PersonData: MyProtocol {
var name:String = ""
init(name:String) {
self.name = name
}
func printData() {
print("[name: \(name).]")
}
}
class MemoData: MyProtocol {
var content:String = ""
init(content:String) {
self.content = content
}
func printData() {
print(content)
}
}
var data:[MyProtocol] = []
data.append(PersonData(name: "kimkc"))
data.append(MemoData(content: "Meeting from 9 AM"))
for obj in data {
obj.printData()
}
MyProtocol requires the printData method. PersonData and MemoData both adopt the protocol even though they are unrelated classes with different properties.
The data array stores values as MyProtocol. Any instance whose class conforms to MyProtocol can be added. The loop then calls printData through the protocol type.
Protocols make it possible to process unrelated classes together through a shared interface.