Interfaces in Swift

Interfaces are named collections of method signatures.

import Foundation

// Here's a basic protocol for geometric shapes.
protocol Geometry {
    func area() -> Double
    func perim() -> Double
}

// For our example we'll implement this protocol on
// `Rect` and `Circle` types.
struct Rect: Geometry {
    let width, height: Double
    
    func area() -> Double {
        return width * height
    }
    
    func perim() -> Double {
        return 2 * width + 2 * height
    }
}

struct Circle: Geometry {
    let radius: Double
    
    func area() -> Double {
        return Double.pi * radius * radius
    }
    
    func perim() -> Double {
        return 2 * Double.pi * radius
    }
}

// If a function parameter has a protocol type, then we can call
// methods that are in the named protocol. Here's a
// generic `measure` function taking advantage of this
// to work on any `Geometry`.
func measure(_ g: Geometry) {
    print(g)
    print(g.area())
    print(g.perim())
}

// In the main part of the program
let r = Rect(width: 3, height: 4)
let c = Circle(radius: 5)

// The `Circle` and `Rect` struct types both
// conform to the `Geometry` protocol so we can use
// instances of these structs as arguments to `measure`.
measure(r)
measure(c)

To run the program, save it as Interfaces.swift and use swift command:

$ swift Interfaces.swift
Rect(width: 3.0, height: 4.0)
12.0
14.0
Circle(radius: 5.0)
78.53981633974483
31.41592653589793

In Swift, we use protocols instead of interfaces. Protocols define a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The struct or class then provides an actual implementation of those requirements, thereby adopting the protocol.

Next example: Enums.