a set of various differently typed items.
This is really just a simple case of iterating over the items in the collection and calling the title setting.
NSMenuItem. That's not going to work as they share no base class that contains a title property.
I want my code to capture the intent as much as possible with as little redundancies as possible, so option #1 is out.
NSWindow and NSMenuItem share a common set of behaviors, or more specifically in this case, a single behavior: title.
Now, it seems that they actually already do share this behavior and that it is just not codified. However, if you look at the declaration of each, you'll notice that NSWindow actually returns a String? for title and NSMenuItem returns a String (note the optional vs. non-optional difference).
Ok… that's annoying, but we can work around that!
With the protocol extension HasTitle, we have now codified what the behavior semantics are. It's then trivial to implement that appropriately for each type that you want to share this HasTitle codification.
Now, unfortunately, Swift needed a little bit of type annotation help to make it all work 100%, but we've done it. With one simple protocol and two easy class extensions, our usage code has become significantly cleaner, easier to update, and less error prone.
Could we bring this technique back to ObjC? Of course. Just write the simple for-loop to begin with. However, you'll probably stop there because that is all that is needed to make the ObjC side happy as we can send messages to any object instance; we can completely forgo the HasTitle protocol.
However, that is the part that I think it vastly more important as it's that protocol that leads us into thinking about better composition models. I hope to do a longer blog post about that at another time.