Swift Classes vs. Structs: You’re doing it wrong

OK, you’re probably doing it right, but I’ve figured out that I was thinking about Swift the wrong way.

As I first dabbled in Swift, I did what I suspect a lot of people did and approached it as translating Objective-C patterns to a new language. It was the wrong approach, like translating English to Spanish by adding an ‘o’ to the end of each word.

After my initial forays into Swift, I put it on the back burner as I prepared the iOS version of SongTool for release. I had originally wanted to write SongTool in Swift, but quickly realized that Core Audio support in Swift was nowhere near where I needed it to be. So, I returned to Objective-C for SongTool, while still keeping an eye on the new kid. I’m glad I did.

The main thing I missed about Swift early on was the power of structs. From reading the documentation, I knew they were powerful (and are actually at the heart of Swift types), but I had no idea how powerful until I ran across a couple of videos discussing the use of value types (structs and enums) vs. reference types (classes).

First came Andy Matuschak’s talk on value types for realm.io. He laid out a compelling case for using value types as much as possible, but I was still having a hard time seeing how to do this in the real world. This morning, I finally got around to watching a talk on Make School by Benjamin Encz that provided a concrete example of Matuschak’s concepts. These videos are about 45 minutes each, and go a long way toward bridging OOP and the Functional Programming elements of Swift.

I’m not saying that classes don’t have a place in Swift (they absolutely do), but they will not be the first tool I reach for. To return to the language analogy, I want to think in Swift instead of just translating into it, and this means embracing all of it with fresh eyes and an open mind.

Leave a Reply