Using didSet to configure IBOutlet views…

Swift’s didSet property observer is a great way to configure views linked via IBOutlet. It allows you to set properties that need to be dynamic at runtime or that can’t be configured via Interface Builder:

class MyClass {
@IBOutlet weak var outputLabel: UILabel! {
didSet {
// Ensure that the label wasn't just set to nil.
guard let outputLabel = self.outputLabel else { return }
// Set the text color based on the user's style choices.
outputLabel.textColor = StyleManager.sharedManager().outputLabelColor
// Set the label to use fixed-width numbers.
let oldDescriptor = outputLabel.font.fontDescriptor()
let fontAttributes = [
UIFontDescriptorFeatureSettingsAttribute : [
UIFontFeatureTypeIdentifierKey : kNumberSpacingType,
UIFontFeatureSelectorIdentifierKey : kMonospacedNumbersSelector
let newDescriptor = oldDescriptor.fontDescriptorByAddingAttributes(fontAttributes)
outputLabel.font = UIFont(descriptor: newDescriptor, size: 0)

However, it’s worth keeping a simple rule in mind when you go about configuring your views with didSet:

Don’t reference other IBOutlet views or implicitly unwrapped properties in your didSet block.

The reason for this is simple: you have no way of knowing which order your IBOutlets will be set in, so the other view or property you’re trying to access may not be there. At best, you’re going to be nil-checking a lot and end up only partially configuring your views, requiring follow-up elsewhere in code. At worst, you’re going to accidentally force-unwrap a nil and crash your app.

It’s okay to reference external objects, as seen in the call to the StyleManager above, as long as they’re non-optional and not subject to race conditions. The proper place to establish things like view layout relationships or properties from one view that copy the properties from another is still in viewDidLoad.