I create an enumeration contains all months of the year. The computed value of the enumeration returns the university semesters based on the input month
enum Month{
case January, February, March, April, May, June, July, August, September, October, November, December
var schoolSemester: String {
switch self {
case .April, .September, .October, .November, .December:
return "Autumn"
case .January, .February, .March, .April, .May:
return "Sping" // Here comes the warning
default:
return "Not in the school year"
}
}
}
var whichSemester = Month.February
print(whichSemester.schoolSemester)//even though the warning says this will never be executed, but it was executed!
Question1: Why Xcode keeps telling me that the second case will never be executed (which is wrong! I did execute the case by assign the February to the Month)
Question 2: Is calculated property a Lazy property?
Thanks a lot for your time and help
The compiler issues a warning because you apparently mistyped
.August
as .April
in the first case, so that .April
occurs in
both cases.
The compiler could not notice that you omitted .August
because you used
a default case. It is therefore better to list all possible enumeration
values explicitly instead:
var schoolSemester: String {
switch self {
case .April, .September, .October, .November, .December:
return "Autumn"
case .January, .February, .March, .April, .May:
return "Spring"
case .June, .July:
return "Not in the school year"
}
Now the compiler issues both a warning and an error
warning: case will never be executed case .January, .February, .March, .April, .May: error: switch must be exhaustive, consider adding a default clause
and the code does not compile. It forces you to check all cases
again, and you'll quickly notice that .August
is missing.