Menu
CoddyTech

Switch and Patterns

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

Rust match and Swift switch both support exhaustive pattern matching, including tuples, wildcard components and alternatives. The origin case must precede the broader axis alternatives because the origin also lies on an axis. Rust uses | between alternative patterns and a wildcard arm for the remaining values; Swift uses a comma between case patterns and default here. Neither construct automatically falls through to the next branch. Matching can bind payload values after identifying a shape, but ownership and borrowing determine whether a Rust match moves data. Swift has a different value and reference model, so preserve both the decision and the required data lifetime.

Rust

fn location(x: i32, y: i32) -> &'static str {
    match (x, y) { (0, 0) => "origin", (0, _) | (_, 0) => "axis", _ => "plane" }
}

fn main() {
    println!("{}", location(0, 0));
    println!("{}", location(0, 5));
    println!("{}", location(2, 3));
}

Swift

func location(_ x: Int, _ y: Int) -> String {
    switch (x, y) {
    case (0, 0): return "origin"
    case (0, _), (_, 0): return "axis"
    default: return "plane"
    }
}
print(location(0, 0))
print(location(0, 5))
print(location(2, 3))
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 Rust Developers

Practice on your own: Swift playground