Swift
Beginner
1 min read
Protocol Basics
Example
// Protocol definition
protocol Describable {
var description: String { get }
func describe() -> String
}
// Protocol extension with default implementation
extension Describable {
func describe() -> String {
return "Description: \(description)"
}
}
// Struct conforming to protocol
struct Car: Describable {
var make: String
var model: String
var year: Int
var description: String {
"\(year) \(make) \(model)"
}
// describe() provided by extension
}
// Protocol inheritance
protocol Printable: Describable {
func print()
}
extension Printable {
func print() {
Swift.print(describe())
}
}
// Protocol composition
protocol Named { var name: String { get } }
protocol Aged { var age: Int { get } }
func greet(_ person: Named & Aged) -> String {
"Hello \(person.name), you are \(person.age)"
}
struct Person: Named, Aged {
let name: String
let age: Int
}
let alice = Person(name: "Alice", age: 30)
print(greet(alice))
// Protocol as type (existential)
let items: [any Describable] = [Car(make: "Toyota", model: "Camry", year: 2023)]