Deciphering an enumeration in a function

You can rewrite the function that determines the semester so that it uses enumeration values instead of string-matching:

func semester(for month: Month) -> String { switch month {

case Month.august, Month.september, Month.october, Month.november, Month.december:

return "Autumn"

case Month.january, Month.february, Month.march, Month.april, Month.may:

return "Spring" default:

return "Not in the school year"

}

}

Since Swift is strongly-typed and uses type inference, you can simplify semester(for:) by removing the enumeration name in places where the compiler already knows the type. Keep the dot prefix, but lose the enumeration name, as shown below for the cases inside the switch statement:

func semester(for month: Month) -> String { switch month {

case .august, .september, .october, .november, .december: return "Autumn"

case .january, .february, .march, .april, .may: return "Spring"

default:

return "Not in the school year"

}

}

Also recall that switch statements must be exhaustive with their cases. The compiler will provide you a warning if you don’t. When your case patterns are String elements, you need a default case because it’s impossible to create cases to match every possible String value. However, enumerations have a limited set of values you can match against. So if you have cases for each member value of the enumeration, you can safely remove the default case of the switch statement:

func semester(for month: Month) -> String { switch month {

case .august, .september, .october, .november, .december: return "Autumn"

case .january, .february, .march, .april, .may: return "Spring"

case .june, .july: return "Summer"

}

}

That’s much more readable. There is another huge benefit to getting rid of the default. If in a future update someone added .undecember or .duodecember to the Month enumeration, the compiler would automatically flag this and any other switch statement as being non-exhaustive allowing you handle the case specifically.

You can test this function in a playground like so:

var month = Month.april semester(for: month) // "Spring"

month = .september semester(for: month) // "Autumn"

The variable declaration for month uses the full enumeration type and value. In the second assignment, you can use the shorthand .september, since the compiler already knows the type. Finally, you pass both months to semester(for:), where a switch statement returns the strings "Spring" and "Autumn" respectively.

results matching ""

    No results matching ""