Tsallaka zuwa abun ciki
Justice Tech School

Swift Protocols

A protocol lists requirements a type must meet, like an interface. Structs, classes and enums can all adopt protocols. Extensions can give default implementations.

Example
protocol Shape { func area() -> Double }
struct Circle: Shape { var r: Double; func area() -> Double { 3.14 * r * r } }
struct Square: Shape { var s: Double; func area() -> Double { s * s } }
for s in [Circle(r: 1), Square(s: 2)] as [Shape] { print(s.area()) }

Exercise

Declare a protocol.

 Shape { }

Quiz Test

Which can adopt a protocol?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.