Closures and Transformations
Lesson 24 of 48 in Coddy's Swift for Rust Developers course.
Rust iterator map is lazy: collecting drives the transformation and creates the vector. Closure captures are inferred as borrows or moves according to use, with move available to request moving captured values. Swift Array.map eagerly produces an array, and its closure syntax can use shorthand arguments such as $0. Reduce combines values from an initial accumulator. Both examples square three integers and sum the resulting values. A Rust iterator chain and a Swift collection operation can have different evaluation timing and ownership effects, so preserve side-effect order deliberately rather than assuming similar names imply identical execution models.
Rust
fn main() {
let squares: Vec<i32> = [2, 3, 4].iter().map(|x| x * x).collect();
println!("{}", squares.iter().map(i32::to_string).collect::<Vec<_>>().join(" "));
println!("{}", squares.iter().sum::<i32>());
}
Swift
let squares = [2, 3, 4].map { $0 * $0 }
print(squares.map(String.init).joined(separator: " "))
print(squares.reduce(0, +))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 Rust 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