Swift Access Controls: How To Avoid The ‘Private’ Keyword Repetition

A few weeks ago, I contributed an article about Swift functions in objc.io, where I mentioned that I prefer to put all my private methods together at the bottom of my class, separated by a landmark. So I wish there was a way in Swift, like in other languages, to say that all functions below this one are private.

In response, @chromophoreapp had the following idea:

I tried this out today, and really like the result!

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        configureAppearance()
    }

}

// MARK: Private
private extension ViewController {
    
    func configureAppearance() {
        view.backgroundColor = UIColor.purpleColor()
    }
    
}

This approach really reduces the noise in your ViewController, and has the added benefit of not having to write the private keyword over and over again for your private methods.

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.