Wednesday, August 9, 2017

Protocol Composition in Swift and Objective-C

Jesse Squires:

Any protocol in Swift that contains optional members must be marked as @objc. I have written before about avoiding @objc in your Swift code as much as possible. When @objc infiltrates your object graph, nearly everything must inherit from NSObject which means you cannot use Swift structs, enums, or other nice features. This leaves you not writing Swift, but merely “Objective-C with a new syntax”.


A better approach is to split up large protocols into smaller ones, and provide a unique property (like a delegate) for each one.


This design transfers the “optional-ness” from the protocol itself to an additional optional property on the class. If you want headers and footers in your table view, you can opt-in to those by setting titlesDataSource. To opt-out, you can set this property to nil. The same applies to reorderingDataSource, and so on.


Instead of numerous disjoint protocols, you can design a union of protocols. This provides a single, top-level “entry point” to reference. You can extract the optional members of a protocol into a new protocol, then add an optional property for this new protocol on the original protocol. The result is a comprehensive top-level protocol and a set of “nested” protocols.

1 Comment RSS · Twitter

So basically, the language lacks a useful semantic feature, so lets restructure out entire design philosophy but try to make it still sounds like its good engineering…?

Leave a Comment