Closures and Transformations
Lesson 24 of 48 in Coddy's Swift for JavaScript Developers course.
JavaScript closures retain access to lexical bindings, so live observes the later factor value. The factory creates a distinct saved binding initialized from the earlier number, giving frozen a snapshot of that primitive value. Object references captured this way can still refer to mutable shared objects.
Swift closures also capture context, with an explicit capture list able to preserve the current value of an integer. Class captures additionally involve ARC, and weak captures can avoid ownership cycles. Both Array.map examples run eagerly; storing a closure is separate from invoking it or scheduling concurrent work.
JavaScript
Complete JavaScript console program:
main.js
let factor = 2;
const live = x => x * factor;
const frozen = (saved => x => x * saved)(factor);
factor = 3;
console.log([1, 2].map(live).join(","));
console.log(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
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 JavaScript 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