Extensions in Swift seem to have a lot of promise, but I've not really found a way of using them to structure large/complex types that feels just right. I'd like to know how others are using extensions and maybe get some ideas to help structure my code.
Here are some of the obvious uses for extensions (some of these are even recommended in "The Swift Programming Language"), and some of the issues I've run into when using them:
Use Case: separate logical or semantic sections of code
Problems:
- Since extensions can only contain functions or computed properties, any stored properties that otherwise relate to this section of code still have to go in the "main" declaration of the type.
- If the class is intended for extending, any vars or functions intended for overriding cannot be placed in the extension
Result: Code organized into logical & semantic sections... Except when it isn't
Use Case: separating large types into multiple files
Problems:
- Since the 'private' visibility modifier is file- not type-specific, there is no way to hide internal implementations from other code (and autocomplete) within a large application.
- see #1 from previous use-case
Result: Otherwise 'private' implementation details of the type are instead effectively 'public' (in application code, there's no practical difference between 'public' and 'internal')
Use Case: separating protocol conformance
Problems:
This generally works fine, unless your implementation happen to run afoul of the above problems.
Result: Fine... unless your protocol conformance needs a stored property for its implementation, then... Oh well.
Anyway, this post isn't intended to be just a gripe list... I'm genuinely seeking ideas on how to better utilize this language feature, and/or how others get around some of the limitations described above.