Lesson 15 of 15

Protocols

Protocols

A protocol defines a blueprint of methods and properties that conforming types must implement — similar to interfaces in other languages:

protocol Greetable {
    func greet() -> String
}

class Person: Greetable {
    var name: String
    init(_ name: String) { self.name = name }
    func greet() -> String { return "Hello, I'm \(name)" }
}

Protocol as a Type

You can use a protocol as a type to write polymorphic code:

func introduce(_ g: Greetable) {
    print(g.greet())
}

Structs Can Conform Too

struct Robot: Greetable {
    func greet() -> String { return "Beep boop." }
}

Your Task

Define a Shape protocol with an area() -> Int method. Then create a Circle class that conforms to Shape and has an init(_ radius: Int). The area should be radius * radius * 3 (integer approximation of π×r²).

JS Transpiler loading...
Loading...
Click "Run" to execute your code.