Switch It Up

Create a new playground called Switch and set up a switch.

Listing 5.1  Your first switch

import Cocoa

var statusCode: Int = 404
var errorString: String
switch statusCode {
case 400:
    errorString = "Bad request"

case 401:
    errorString = "Unauthorized"

case 403:
    errorString = "Forbidden"

case 404:
    errorString = "Not found"

default:
    errorString = "None"
}

The switch statement above compares an HTTP status code against four cases in order to match a String instance describing the error. Because case 404 matches statusCode, errorString is assigned to be equal to "Not found", as you can see in the sidebar (Figure 5.1). Try changing the value of statusCode to see the other results. When you are done, set it back to 404 ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.