Swift - Matching Numbers in switch case statement

Introduction

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:

Demo

var day = 6
var dayOfWeek: String
switch day {//from   w  w w  .j av a2 s.  com
    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"
    default:
        dayOfWeek = ""
}


print(dayOfWeek) //prints Saturday

Result

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