Closures and Transformations
Lesson 24 of 48 in Coddy's Swift for Ruby Developers course.
Ruby blocks can be passed to methods and converted to callable objects when needed. Array#map returns transformed values, whereas map! changes the array itself. Closures can capture local bindings, and mutation of shared objects inside a block remains a separate effect from constructing the result array.
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 values in order and preserve the input array. Swift closure syntax differs, and its Array value semantics affect shared mutation differently. Keep transformation and formatting separate, and avoid substituting a mutating source operation for a value-producing target one.
Complete Ruby comparison program:
distances = [2, 5, 3]
squares = distances.map { |distance| distance * distance }
puts squares.join(" ")
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 Ruby 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