Closures and Transformations
Lesson 24 of 48 in Coddy's Swift for Go Developers course.
Go functions are values and closures can access surrounding variables. Swift closures also carry behavior and captured context, but their ARC and value semantics need separate attention. Explicit Swift capture lists can capture selected current values or weak class references.
The Go program applies a predicate in a loop, while Swift map eagerly returns an array of transformed results. Both classify the same readings. A Go goroutine or a parallel library call would change concurrency explicitly; merely passing a closure does not make these transformations parallel.
Go: complete program
main.go
package main
import (
"fmt"
"strings"
)
func main() {
values := []int{-2, 0, 5}
negative := func(value int) bool { return value < 0 }
labels := make([]string, 0, len(values))
for _, value := range values { labels = append(labels, fmt.Sprint(negative(value))) }
fmt.Println(strings.Join(labels, " "))
}
Swift: complete program
main.swift
import Foundation
let flags = [-2, 0, 5].map { $0 < 0 }
print(flags.map { String($0) }.joined(separator: " "))Understand captured state and execution timing independently of the transformation formula. A reference to shared mutable state can remain observable through later calls.
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 Go 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