Protocol Basics
A protocol is like a checklist of things a type promises to be able to do, without saying exactly how it does them.
Defining a Protocol
A protocol declares required properties and methods that any conforming type must implement, without providing an implementation itself.
Example: Defining a Protocol
protocol Greetable {
var name: String { get }
func greet() -> String
}
struct Robot: Greetable {
var name: String
func greet() -> String {
return "Beep boop, I am \(name)"
}
}
let robot = Robot(name: "R2")
print(robot.greet())
Login to try C/C++/Java/PHP code in the editor
Multiple Types Conforming to the Same Protocol
Different, unrelated types can all conform to the same protocol, letting you treat them uniformly wherever that protocol is expected.
Example: Multiple Types Conforming to the Same Protocol
protocol Greetable {
var name: String { get }
func greet() -> String
}
struct Human: Greetable {
var name: String
func greet() -> String { "Hi, I am \(name)" }
}
struct Robot: Greetable {
var name: String
func greet() -> String { "Beep, I am \(name)" }
}
let greeters: [Greetable] = [Human(name: "Ana"), Robot(name: "R2")]
for greeter in greeters {
print(greeter.greet())
}
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Confusing a protocol (a contract with no implementation) with a class (a concrete type with real implementation); a protocol on its own can't be instantiated.
- Forgetting a type must implement every requirement listed in a protocol to conform to it -- partial conformance is a compile error.
- Assuming protocols can only be adopted by classes; structs and enums can conform to protocols too.
Chapter Summary
- A
protocoldefines a set of method and property requirements without implementing them. - Any struct, class, or enum can conform to a protocol by implementing all its requirements.
- Conformance is declared with
: ProtocolNameafter the type name. - Protocols enable polymorphism without requiring class inheritance.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: