Component - Protocols
This UI component demonstrates how protocols work in Swift. Protocols define a set of rules or methods that a class or struct must follow. Here, a simple protocol is used to make different shapes provide their area calculation.
This UI component demonstrates how protocols work in Swift. Protocols define a set of rules or methods that a class or struct must follow. Here, a simple protocol is used to make different shapes provide their area calculation.
View > VStack > [Text, Button]
protocol in Swift?Drivable in Swift?protocol followed by the name and curly braces.protocol Greetable {
func greet() -> String
}
struct Person: Greetable {
func greet() -> String {
return "Hello!"
}
}
let p = Person()
print(p.greet())Person adopts Greetable and implements the required greet() method returning "Hello!".p.greet() returns "Hello!", which is printed.protocol Runnable {
func run()
}
struct Athlete: Runnable {
// Missing run() implementation
}Runnable requires a method run() with no return value.Athlete adopts Runnable but does not implement run(), causing a compile error.Vehicle with a property speed that can be read and set. Which of these protocol declarations is correct?{ get set } in the protocol.speed as a variable property with get set. protocol Vehicle { var speed: Int } misses get set, so it's read-only. protocol Vehicle { func speed() -> Int } declares a method, not a property. protocol Vehicle { let speed: Int } uses let, which is not allowed in protocols.Pass the test and this pattern moves unknown