Closures and Transformations
Lesson 24 of 48 in Coddy's Swift for R Developers course.
R functions are values that close over an enclosing environment. Vapply applies a function and checks each result against the supplied template; lapply instead returns a list. Many arithmetic operations are already vectorized, so this explicit callback example teaches transformation rather than claiming a loop is always necessary.
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 programs preserve the input order and produce squares without mutating the original collection. Swift map infers its result element type from the closure, while vapply checks against integer(1L). Keep callback behavior separate from output formatting and from accidental updates to enclosing state.
Complete R comparison program:
distances <- c(2L, 5L, 3L)
squares <- vapply(distances, function(distance) distance * distance, integer(1L))
cat(paste(squares, collapse = " "), "\n", sep = "")
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 R 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