Break out of an outer loop in Swift

March 02, 2017

It’s not uncommon to write a nested for loop, where you need to break out of the outer loop when a condition is met in the inner loop. In some languages you might use a variable for this, but in Swift there’s a cleaner way: labeled statements!

func indexPathFor(_ contact: InviteContact) -> IndexPath? {
    var indexPath: IndexPath? = nil
    
    outer: for sectionIndex in 0...dataSource.sectionCount {
        for (rowIndex, next) in dataSource.contactsFor(sectionIndex).enumerated() {
            if contact == next {
                indexPath = IndexPath(row: rowIndex, section: sectionIndex)
                break outer
            }
        }
    }
    
    return indexPath
}

It’s small things like this that help make Swift code clean, readable and fun to write.

Marc Charbonneau is a mobile software engineer in Portland, OR. Want to reply to this article? Get in touch on Twitter @mbcharbonneau.