Menu
CoddyTech

Closures and Transformations

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

Luau closures capture lexical locals. The live function observes factor after its reassignment, while snapshot introduces a separate saved binding initialized from the earlier number. A captured table value would still share its referenced table, so this is not a general deep-copy mechanism.

Swift closures likewise can observe captured mutable state. A capture list such as [factor] records that value at closure creation; with this numeric value it preserves two. Array.map applies the live closure to each element in order. Choose a live capture or a snapshot deliberately when callbacks outlast the setup code.

Luau

Complete Luau console program:

main.luau

local factor = 2
local live = function(x: number) return x * factor end
local function snapshot(saved: number)
  return function(x: number) return x * saved end
end
local frozen = snapshot(factor)
factor = 3
local values = {1, 2}
local mapped = {}
for i, value in ipairs(values) do mapped[i] = live(value) end
print(table.concat(mapped, ","))
print(frozen(2))

Swift

Complete program; compile the listed files together:

main.swift

import Foundation
var factor = 2
let live = { (x: Int) in x * factor }
let frozen = { [factor] (x: Int) in x * factor }
factor = 3
print([1, 2].map(live).map(String.init).joined(separator: ","))
print(frozen(2))
challenge icon

Challenge

Easy

Implement shortWords(_:limit:): retain words with Character count at most limit and sort them ascending; preserve duplicates. Input is limit 0 through 20 then 0 through 50 lowercase ASCII words of length 1 through 20. Output space-separated results or a blank line.

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 shortWords(["moon","sun","a","sun"], limit: 3) == ["a","sun","sun"] && shortWords([], limit: 4).isEmpty
}
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