Swift - Matching Numbers in switch case statement


A common use of the Switch statement is for matching numbers.

The following code shows how to use the Switch statement to convert a number to the day of week:


var day = 6
var dayOfWeek: String
switch day {//from ww  w .  j ava2  s  .  c o m
    case 1:
        dayOfWeek = "Monday"
    case 2:
        dayOfWeek = "Tuesday"
    case 3:
        dayOfWeek = "Wednesday"
    case 4:
        dayOfWeek = "Thursday"
    case 5:
        dayOfWeek = "Friday"
    case 6:
        dayOfWeek = "Saturday"
    case 7:
        dayOfWeek = "Sunday"
        dayOfWeek = ""

print(dayOfWeek) //prints Saturday


If day contains a number other than a number from 1 to 7, the default case will match and the dayOfWeek variable will be set to an empty string.

Related Topic