Using break statement in switch

The break statement inside a switch can be used when you don’t need a case to have any actual functionality, but want to include it to make your logic easier or clearer. Suppose for example you want to use a switch statement to determine if a given year is a leap year or not. (This is a bit of a contrived example.)

func isLeapYear(year: Int) -> Bool {
    switch (year) {
    case let x where (x % 100) == 0 && (x % 400) != 0:
        break
    case let x where (x % 4) == 0:
        return true
    default:
        break
    }

    return false
}

isLeapYear(2014)    // false
isLeapYear(2000)    // true
isLeapYear(1900)    // false

The first case of the switch statement inside isLeapYear lets you trap the cases where the year is both divisible by 100 and not divisible by 400, since those are sort of the exceptional non-leap years. The break statement in that case means “do nothing”.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)