Menu
Coddy logo textTech

Recap - Shape Calculator

Part of the Object Oriented Programming section of Coddy's Swift journey. Lesson 36 of 57.

challenge icon

Challenge

Hard

Build a shape calculator that combines polymorphism and generics. The protocol Shape requires name, area() and perimeter() (both Double). Implement Rect, Circle (π as 3.14) and Triangle (three sides, area by Heron's formula with sqrt from Foundation). Write a generic function largest<T>(_ items: [T], by key: (T) -> Double) -> T?. Complete report(_:), which returns one line per shape with two decimals (rect: area 12.00, perimeter 14.00), then largest area: circle and largest perimeter: rect, both found with largest.

The supplied code reads lines rect,3,4, circle,2 or tri,3,4,5, builds [any Shape] and prints each returned line.

Your code goes in Shape.swift, Rect.swift, Circle.swift, Triangle.swift and Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation

// Supplied input/output code: keep it as it is
var input: [String] = []
while let line = readLine() { input.append(line) }
var shapes: [any Shape] = []
for line in input {
    let p = line.split(separator: ",").map(String.init)
    let v = p.dropFirst().map { Double($0)! }
    switch p[0] {
    case "rect": shapes.append(Rect(w: v[0], h: v[1]))
    case "circle": shapes.append(Circle(r: v[0]))
    default: shapes.append(Triangle(a: v[0], b: v[1], c: v[2]))
    }
}
for line in report(shapes) { print(line) }

All lessons in Object Oriented Programming

Practice on your own: Swift playground