Blog

Functional Snippet #20: Configuration Values

When you deal with configuring objects, it can be handy to group multiple configuration values together. For example, when configuring table views, it can be handy to group multiple presentation options into one configuration value. Let's assume that we have two kinds of table views in our application: very plain ones (with no header, footer or background view) and fancy ones (with custom headers and footers). As a first step, we could define a configuration struct that holds these custom options:

								struct TableViewConfiguration {
    var headerView: UIView?
    var backgroundView: UIView?
    var footerView: UIView?
}

							

Because we don't have the UITableView source code, we can add an extension to configure it given a TableViewConfiguration value:

								extension UITableView {
    func configure(configuration: TableViewConfiguration) {
       tableHeaderView = configuration.headerView
       backgroundView = configuration.backgroundView
       tableFooterView = configuration.footerView
    }
}

							

Now, we can create two configurations that group together our custom table view configurations:

								let defaultConfiguration = TableViewConfiguration(headerView: nil, 
                                                  backgroundView: nil,
                                                  footerView: nil)
let fancyConfiguration = TableViewConfiguration(headerView: myHeader, 
                                                backgroundView: nil,
                                                footerView: myFooter)

							

These can be readily used and shared all over our code base. Because they are defined using let, they are immutable. However, the properties are defined as var, so we can easily make a copy if we need to customize one of the configurations by a little bit:

								var myConfig = fancyConfiguration
myConfig.backgroundView = ...

							

Stay up-to-date with our newsletter or follow us on Twitter .

Back to the Blog

Recent Posts