Protocols as Contracts
Define behavior contracts independent of types.
What Is a Protocol?
A protocol defines a blueprint of methods, properties, and other requirements that a conforming type must implement. It is a contract: any type that adopts it promises to provide everything the protocol declares.
protocol Greetable {
var name: String { get }
func greet() -> String
}Conforming to a Protocol
A type conforms by adopting the protocol and supplying every requirement. Here a struct fulfills both the name property and the greet() method.
protocol Greetable {
var name: String { get }
func greet() -> String
}
struct Person: Greetable {
let name: String
func greet() -> String { "Hello, I am " + name }
}
let p = Person(name: "Ada")
print(p.greet())All lessons in this course
- Protocols as Contracts
- Default Implementations in Extensions
- Protocol Composition
- Conditional Conformance