Complex Datatypes

This morning I’m on Day 2 of 100 Days of Swift. Today I worked through complex datatypes: arrays, dicts, sets, tuples, and enums. I expected to not learn a lot today, but I was surprised by how much I wasn’t already familiar with.

First up, sets and tuples in Swift. While I knew that Swift had sets and tuples, I hadn’t consciously used them before. I’ve used tuples a fair amount in Python, and it was cool to see the Swift syntax was mostly analogous. In Python I’m a fan of namedtuple for lightweight structured data. However, in Swift I imagine you’d want to use structs instead?

Another thing that was new to me was default values for dictionaries. While looking further into them, I also discovered an optional unwrapping syntax with default that was completely new to me:

let favoriteIceCream = [
    "Paul": "Chocolate",
    "Sophie": "Vanilla",
]
favoriteIceCream["Charlotte", default: "Unknown"]
favoriteIceCream["Charlotte"] ?? "Unknown"

The third thing that was new to me was associated values for enums. I’d come across this while reading about Swift before, but never used it or actively put it into practice.

enum Activity {
    case bored
    case running(destination: String)
    case talking(topic: String)
    case singing(volume: Int)
}
let footie = Activity.talking(topic: "football")
let crooning: Activity = .singing(volume: 19)

I did a little further exploration, and you can combine associated values with Swift’s switch statement for some cool pattern matching effects:

switch crooning {
case .singing(let volume) where volume > 30:
    print("singing loudly")
case .singing(let volume) where volume <= 30:
    print("singing quietly")
default:
    print("dunno")
}

This was my first 30 minutes. With my second 30 minutes I’m going to start working on getting S3 support working for MFArtist again, since the library I had been using hasn’t been updated for Swift 4.2.

Only 98 days left!