Closures and Transformations
Lesson 24 of 48 in Coddy's Swift for Lua Developers course.
Lua functions are first-class values and can close over lexical locals. The small map helper accepts a transformation and creates a dense result sequence. Standard Lua does not supply a universal table.map, so the iteration policy is explicit: this helper visits only the sequence part through ipairs.
Swift Array.map transforms each element into a new array. A closure can infer its parameter type from context, use a single-expression return and refer to shorthand arguments such as $0. Captured state still deserves attention; a closure is not automatically pure merely because its body is short.
Both examples square each distance and preserve the element order. The source helper and target standard-library operation have the same purpose for these dense arrays. Keep transformation separate from formatting, and avoid mutating a shared source table accidentally in the callback.
Complete Lua comparison program:
local distances = {2, 5, 3}
local function map(values, transform)
local result = {}
for i, value in ipairs(values) do result[i] = transform(value) end
return result
end
local squares = map(distances, function(value) return value * value end)
print(table.concat(squares, " "))
Complete Swift comparison program, compiled from these files:
main.swift
let distances = [2, 5, 3]
let squares = distances.map { $0 * $0 }
print(squares.map { String($0) }.joined(separator: " "))Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Lua Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog MergePractice on your own: Swift playground