Closures and Transformations
Lesson 24 of 48 in Coddy's Swift for C Developers course.
Standard C function pointers refer to functions without automatically carrying a captured local environment. A callback needing state commonly receives an additional context pointer. Swift closures have function types and can capture surrounding values, with trailing-closure syntax and shorthand names such as $0.
The C helper calls a predicate explicitly in a loop; Swift map creates an array of transformed values. Both determine whether each reading is negative. Capturing a Swift class reference can participate in ARC ownership cycles, while a C context pointer needs a valid lifetime supplied by the program.
C: complete program
main.c
#include <stdio.h>
#include <stdbool.h>
static bool negative(int value) { return value < 0; }
static void flags(const int *values, int count, bool (*rule)(int)) {
for (int i = 0; i < count; ++i) printf("%s%s", i ? " " : "", rule(values[i]) ? "true" : "false");
putchar('\n');
}
int main(void) { int values[] = {-2, 0, 5}; flags(values, 3, negative); return 0; }
Swift: complete program
main.swift
import Foundation
let flags = [-2, 0, 5].map { $0 < 0 }
print(flags.map { String($0) }.joined(separator: " "))Passing behavior does not imply parallel execution. The displayed transformations are ordinary sequential computations.
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 C 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