Menu
CoddyTech

Switch and Patterns

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

Luau uses ordered if checks rather than a built-in switch or tuple-pattern syntax. This function handles the more specific origin case before the broader vertical case. Reversing those checks would classify the origin differently, so branch ordering is part of the behavior.

Swift switch can match tuples and wildcard components. Its cases are checked in order, must cover the possibilities, and do not fall through automatically. The first tuple pattern handles (0, 0), then (0, _) handles other vertical points. Preserve both the conditions and their precedence when porting.

Luau

Complete Luau console program:

main.luau

local function axis(x: number, y: number): string
  if x == 0 and y == 0 then return "origin" end
  if x == 0 then return "vertical" end
  return "other"
end
print(axis(0, 9))

Swift

Complete program; compile the listed files together:

Functions.swift

import Foundation
func axis(_ x: Int, _ y: Int) -> String {
    switch (x, y) {
    case (0, 0): return "origin"
    case (0, _): return "vertical"
    default: return "other"
    }
}

main.swift

import Foundation
print(axis(0, 9))
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 Luau Developers

Practice on your own: Swift playground