Last Updated: February 25, 2016
·
1.138K
· dmichaelavila

Swift: The Optionals Heuristic

I've been working on various small apps since the release of Swift to familiarize myself with the language and some of the new stuff in iOS 8. This is just a quick tip on a pattern for how I've been using the language's optionals feature.

The heuristic I'm using so far is: Use the if-let-optional syntax whenever a block of code depends on a variable having a value. A contrived example, let's say you have an update method on a view for a contact:

func update() {
    if let firstName = self.firstName {
        self.firstNameLabel.text = firstName
    }

    if let middleName = self.middleName {
        self.middleNameLabel.text = middleName
    }

    if let lastName = self.lastName {
        self.lastNameLabel.text = lastName
    }
}

There might be some handy mechanism I don't know about to shorten up this example, but just consider how the optionals are being used. Basically, firstName, middleName, and lastName are only updated if there is something in them to use.