Structs, part 1

Posted on Sun 16 February 2020 in swift

I'm done with a full week of 100 Days of Swift! For some reason, structs make me happy. I just like them. They were exotic and cool when I was learning C to hack on the Linux kernel. They're still cool today, now that value types and immutability are the hotness.

Two things to cover: property observers and mutating methods. Property observers are kinda like KVO, giving you a convenient place to do something when a property will be or was set. The mutating keyword lets you safely mark which methods can change properties inside the struct, the implication being that these mutating methods will only be callable on variable instances of the struct.

struct Observation {
    var taxon: Taxon
}

struct Taxon {
    var commonName: String
    var scientificName: String
    var seenCount: Int {
        didSet {
            print("Another lovely \(commonName)!")
        }
    }

    mutating func createObservation() -> Observation {
        seenCount += 1
        return Observation(taxon: self)
    }
}

No annoyances today! ^_^