Menu
CoddyTech

Bindings and Mutation

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

Luau table variables hold references. A local declaration or an array type annotation does not freeze the table, and table.clear through an alias clears the same underlying object. Static annotations constrain checked operations, while table.freeze is a separate runtime operation and is shallow.

Swift let fixes a binding, and an Array is a value type. Clearing a var copy leaves the original let-bound array with its two entries. A mutable Swift binding still has a fixed static type. Distinguish binding reassignment, container mutation and shared reference elements when choosing a port's declarations.

Luau

Complete Luau console program:

main.luau

local pending: {string} = {"upload", "index"}
local alias = pending
table.clear(alias)
print(tostring(#pending) .. " " .. tostring(#alias))

Swift

Complete program; compile the listed files together:

main.swift

import Foundation
let pending = ["upload", "index"]
var copy = pending
copy.removeAll()
print(pending.count, copy.count)
challenge icon

Challenge

Easy

Implement offset(_ value: Int) -> Int: add 7 to a value. Input is one integer from -1000 through 1000; output is the resulting integer.

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 offset(31) == 38 && offset(-8) == -1 && offset(31) == 38
}
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