Tiny Swift idioms in ObjC
I got a little distracted this morning. While fixing a nil
-insertion-in-collection bug in Nutshell’s Mac app, I really wanted to write a Swift-style if let
binding, but of course that’s not possible in Objective-C.
With a hint from Jackson and help from Justin, I ended up with this macro which works very nicely:
That’s about as nice as we can make it look with C’s macro syntax.
I went on to implement two versions of Swift-style as!
and as?
casts:
At first glance, the object-oriented NSObject
category seems nicer. But I think I actually prefer the macro-based approach, for two reasons:
- Callers don’t have to deal with the verbosity of the
+class
message send - The
NSObject
category should never be used in Swift, but it’s still available. The macros aren’t exported to Swift, meaning we don’t provide a duplicate of something native to that language.
Updated to add: and I finally wrote a little lazy getter macro. I should’ve done this ages ago.
Updated to add: include all these in your project with this header.