Discuss how to use Swift’s type system to enforce coding standards and improve code safety.

Instruction: Provide examples of leveraging Swift’s type system to reduce errors and enforce coding conventions.

Context: This question explores the candidate's ability to utilize Swift's strong type system for improving code quality, safety, and adherence to project-specific coding standards.

Updated

Official answer

Use types to make invalid combinations harder to express, then validate values and behavior at runtime. Distinct nominal identifiers prevent mixing domains that would otherwise both be strings. A failable initializer can enforce a value range; a plain Int cannot express that range by itself.

This complete example combines domain types, an optional lookup and checked arithmetic:

struct UserID: Hashable { let rawValue: String }
struct OrderID: Hashable { let rawValue: String }
struct Percentage {
    let value: Int
    init?(_ value: Int) {
        guard (0...100).contains(value) else { return nil }
        self.value = value
    }
}
enum TotalError: Error { case overflow }
func checkedTotal(_ values: [Int]) throws -> Int {
    var total = 0
    for value in values {
        let (next, overflow) = total.addingReportingOverflow(value)
        guard !overflow else { throw TotalError.overflow }
        total = next
    }
    return total
}
func display(_ id: UserID) -> String { id.rawValue }
let names = [UserID(rawValue: "u1"): "Jane"]
assert(names[UserID(rawValue: "missing")] == nil)
assert(Percentage(101) == nil)
assert(Percentage(100)?.value == 100)
let total = try checkedTotal([1, 2, 3])
assert(total == 6)
assert(display(UserID(rawValue: "u1")) == "u1")

Passing an OrderID to display is a compiler error. Using typealias for both identifiers would not create that distinction. The empty sum is zero; an addition outside Int's representable range throws instead of trapping. Missing data remains distinguishable from an actual zero value.

Enums can represent mutually exclusive workflow states and allow exhaustive switching. Protocols and generic constraints check required interfaces and type relationships, but cannot prove that an implementation has the intended business behavior. Likewise, an endpoint enum prevents unsupported enum cases in source, not server errors, authorization failures or a typo inside a declared path.

Optionals, access control and concurrency checking help, but force unwraps, unsafe APIs and incorrect validation can still fail. Naming and formatting conventions need review or linting; they are not generally enforced by Swift's type system.

Swift generics and associated types, Optionals and type safety, Advanced arithmetic operators

Related Questions