Menu
CoddyTech

Switch and Patterns

Lesson 11 of 48 in Coddy's Swift for GDScript Developers course.

GDScript match selects a matching pattern and supports several patterns sharing a branch. Swift switch has its own richer pattern syntax and requires exhaustive coverage. An open set such as all strings generally needs a default for values not explicitly listed.

A Swift case can contain comma-separated alternatives or an appropriate range pattern. It does not implicitly fall through to the next body. Use break when a case intentionally does nothing, rather than adding it as though each body always needs to suppress fallthrough.

The source uses a wildcard match branch and Swift uses default to make unknown commands explicit. The task switches over integers, so adapt the same coverage reasoning to its input domain.

Complete GDScript comparison program:

extends SceneTree

func _init():
    var command = "pause"
    match command:
        "pause", "stop":
            print("idle")
        _:
            print("running")
    quit()

Complete Swift comparison program, compiled from these files:

main.swift

let command = "pause"
switch command {
case "pause", "stop": print("idle")
default: print("running")
}
challenge icon

Challenge

Easy

Implement dayKind(_:). Input is an integer -10 through 20. Days 1 through 5 return work, 6 or 7 return rest, and every other value returns invalid.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return dayKind(3) == "work" && dayKind(7) == "rest" && dayKind(-1) == "invalid"
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for GDScript Developers

Practice on your own: Swift playground