Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialBoaz Keren Gil
18,947 PointsSwitch overkill
It seems in this video that we are using switch also when its not needed. For example:
func muteNotifications(dayType: DayType) -> Bool {
switch dayType {
case DayType.Weekend: return true
case DayType.Weekday: return false
}
}
can be:
func muteNotifications(dayType: DayType) -> Bool {
if dayType == DayType.Weekend {
return true
} else {
return false
}
}
Isn't it a bit overkill to use a switch here?
2 Answers
Grant Jason
10,713 PointsBoth answers make sense and definitely work, however in the scope of that particular course switch statements work much better when using enumerations since the compiler will actively search for exhaustiveness. In addition, the switch statement is more readable since you can tell just by looking at the code that weekends will return true for muteNotifications while weekdays will return false.
faraz
Courses Plus Student 21,474 PointsYou're right, in this particular example a switch statement statement could be considered "overkill". For succinctness I would suggest the following:
func muteNotifications(dayType: DayType) -> Bool {
return dayType == DayType.Weekend
}
This combines the return statement with the equality check. In cases where you would be checking more values, I would highly recommend a switch statement for the reasons Grant mentioned.
Let me know if you are confused or have any other questions!
Jhoan Arango
14,575 PointsJhoan Arango
14,575 PointsHello:
I agree with Grant Jason. Also apple does recommend to use switch statements when dealing with enums.
My two cents :)
But you make a fair point, and it's also a "coding" style depending on how you like your code to look.
Happy coding