If you want to make Swift programmer shudder, just whisper the words “associated types.” They’re one of the few Swift language typing features you’re unlikely to find in other programming languages, so they can take some getting used to. Last week I tried to write a seemingly simple function, and ended up spending most of my day diving down the associated type rabbit hole. This post is going to explain how I (eventually) wrote the “simple” function, and hopefully teach you about associated types, generic constraints and “where clauses” along the way!
I wanted a function that would:
Let me tell you about a job I worked back in the good old days. It was 2017. A simpler time. Phones had apps, Wikipedia was free, and Canada still existed. It was a cold November evening, and I was out looking for women. Not like that. This was for a job. I’d been hired by Thomas Talakip, billionaire CEO of popular taxi-replacement app DriveCo, because women were going missing. Smart, well-paid engineering women were disappearing from the DriveCo office. I met Thomas at his boardroom/gym/cereal bar (hey, space is tight in the Bay) and got to work.
Sarah woke up gasping for air. She’d been having the most peculiar dream. Its details were already slipping her mind, leaving nothing but a vague sense of unease. Something about… animals? Bugs? Whatever they were, they had several more legs than she.
Bristling faintly at this injustice, Sarah hit her still-ringing alarm and ran to the shower. Its warm jets washed away both sweat and unease. She emerged clear-headed, the dream forgotten.
Sunlight streamed over her suburban garden and through the kitchen window as Sarah prepared breakfast. …
I write fiction and code. Australian moved to Austin, Texas.