Your first enumeration
Your challenge: construct a function that will determine the school semester based on the month. One way to solve this would be to use an array of strings and match them to the semesters with a switch statement:
// 1
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
// 2
func semester(for month: String) -> 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"
}
}
// 3
semester(for: "April") // Spring
Here’s what’s happening in that code:
- You list out all the months in a year.
- The function will return the semester to which the month belongs.
Running this code in a playground, you can see that the function correctly returns "Spring". But as I mentioned in the introduction, you could easily mistype a string. A better way to tackle this would be with an enumeration.