Swift Optionals

Posted on Thu 20 February 2020 in swift

Today I'm doing 100 Days of Swift at 36,000 feet, flying from SF to New York, to go to a retreat with the Visipedia folks at Cornell Tech. The good news is that there's free WiFi on the flight, so I was able to watch the youtube videos. The bad news is that the 100 Days of Swift website is blocked, perhaps because of the word "hack" in the domain name? C'mon JetBlue, that's just silly.

Today we covered Optionals, another fun core Swift feature. Cool to see the failable initializer syntax, that seems to be used heavily in Decodable and I could probably find a use for it in iNat.

Something I'd forgotten about is nil coalescing, which I can show off here, using a tidbit of my Taxon example from yesterday.

protocol Taxon {
    var scientificName: String { get set }
    var commonName: String? { get set }
    func name() -> String
}

extension Taxon {
    func name() -> String {
        return commonName ?? scientificName
    }
}

And there's the optional try syntax, which seems like a nice way to simplify error handling code without the entire do/try/catch syntax.

enum BrewError: Error {
    case FillWater
}

struct CoffeeMachine {
    var name: String
    var waterLevel: Double
    func brew() throws -> String {
        if waterLevel < 0.3 {
            throw BrewError.FillWater
        } else {
            return "A Nice Cuppa"
        }
    }
}

let marzocco = CoffeeMachine(name: "La Marzocco", waterLevel: 0.0)
if let cup = try? marzocco.brew() {
    print(cup)
} else {
    print("No coffee today")
}

No iPad annoyances today, just the odd WiFi. Which also doesn't allow ssh, so no blog update until I reach NYC.