What are Swift protocols?
Answer
Protocols define a blueprint of methods, properties, and requirements that conforming types must implement. They're Swift's primary mechanism for abstraction and polymorphism — similar to interfaces in other languages but more powerful. Declaring a protocol: protocol Drawable { var color: UIColor { get } // Read-only property requirement func draw() // Method requirement func resize(to size: CGSize) // Another method }. Conforming to a protocol: struct Circle: Drawable { var color: UIColor = .red func draw() { /* draw circle */ } func resize(to size: CGSize) { /* resize */ } } struct Square: Drawable { var color: UIColor = .blue func draw() { /* draw square */ } func resize(to size: CGSize) { /* resize */ } }. Protocol as a type: func render(shapes: [any Drawable]) { for shape in shapes { shape.draw() } } let shapes: [any Drawable] = [Circle(), Square()] render(shapes: shapes). Protocol extensions: provide default implementations — types get behavior for free: extension Drawable { func drawWithBorder() { draw() // drawBorder } }. Protocol composition: func process(item: Saveable & Printable) { }. Protocols with associated types: protocol Container { associatedtype Item func add(_ item: Item) func get(at index: Int) -> Item }. Protocol-Oriented Programming (POP) is Swift's design philosophy — prefer protocols over inheritance.