Swift: How To Name Your Extensions
One of my favorite patterns in iOS programming with Swift is to create multiple extensions throughout my files to keep related methods together. For example, every time my ViewController conforms to a protocol, I keep the protocol methods together in an extension. Same goes for multiple private styling methods or private cell configuration methods in a table view, etc.
The only thing missing from this pattern was that I was unable to name the extensions. Instead, I had to use // MARK:
everywhere to keep track of the groupings. I mentioned this to @allonsykraken the other day, and he showed me a simple trick for this – using typealias
!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() styleNavigationBar() } } private typealias TableViewDataSource = ViewController extension TableViewDataSource: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("identifier", forIndexPath: indexPath) return cell } } private typealias TableViewDelegate = ViewController extension TableViewDelegate: UITableViewDelegate { func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 64.0 } } private typealias ViewStylingHelpers = ViewController private extension ViewStylingHelpers { func styleNavigationBar() { // style navigation bar here } } |
I’m sure you’re now wondering the first thought that popped into my head when I saw this – what about the groupings in the Xcode nav bar?!!! Don’t worry, it’s all there!
Let me know what you think about naming your extensions like this in the comments! Would love feedback as I’m still deciding how much I like this vs just using MARK:
here.