Dcpyfosqs4gggkqvcjm9
SkillsCast

Bringing Swift enums to Objective-C with macros

30th March 2017 in London at CodeNode

There are 33 other SkillsCasts available from iOSCon 2017 - The conference for iOS and Swift Developers

Please log in to watch this conference skillscast.

626807850 640

Swift enums allow us to clearly, concisely, and correctly model information. Without these algebraic data types, it's common to resort to poorly representing information with nullables. Extra nullables lead to unnecessary error checking and crashes, and crashes lead to apps that no one wants to use. Swift enums, otherwise known as algebraic data types, are present in all self-respecting *modern* programming languages. Unfortunately, Objective-C has been around for a while, and does not have a tool like Swift's enum.

In Objective-C you can achieve similar clear and correct expressive power if you sacrifice concision, with a mixture of inheritance and blocks, or by using the visitor pattern. Due to the massive amount of boilerplate you need, you don't reach for these patterns nearly as often as you should. However, you have a tool to manage boilerplate in Objective-C -- preprocessor macros! Despite the limitations of the macro substitution system, with a few macro tricks, you can build a massive macro that can give us algebraic data types with none of the boilerplate. You can declare our types just as you would with Swift enums!

ONE_OF(PIBarCode,

CASE(QrCode, NSString *, code),

CASE(Upc, NSNumber *, num1, NSNumber *, num2, NSNumber *, num3, NSNumber *, num4)

)

In this talk, Brandon will cover why algebraic data types matter, how it's possible to represent them in Objective-C (albeit verbosely), how you can remove the verbosity with macros, and the downsides and upsides of using this one-of macro.

Brandon is passionate about finding and sharing ways to write clean, maintainable code, increasing our industry's productivity. Features of modern programming languages, like Swift's enum, helps you to write correct code on the first try -- functional programming can get us there.

YOU MAY ALSO LIKE:

Thanks to our sponsors

Bringing Swift enums to Objective-C with macros

Brandon Kase

"Brandon Kase brings typed functional programming to weird places. He has shipped production code on Android with Kotlin, iOS with Swift and React Native, and Web with JS/Flow/React. Brandon is an iOS core-experience engineer at Pinterest who came across functional programming while pursuing a B.S. in Computer Science from Carnegie Mellon University. Brandon is excited that strong static typing and functional programming are becoming mainstream, and believes that techniques once reserved for academia will help industry produce more reliable software. He is in general fascinated by anything and everything related to well-designed programming languages and libraries.