Menu
CoddyTech

Closures and Transformations

Lesson 24 of 48 in Coddy's Swift for Java Developers course.

Java lambdas implement functional interfaces such as Function. Swift closures have function types and can be passed directly to operations such as map. A Swift closure written after a function call can use trailing-closure syntax; shorthand names such as $0 refer to its parameters.

The examples convert sensor readings into flags indicating whether each reading is negative. Java streams produce a new result through a terminal operation. Swift map returns an array of the transformed values. Java captured local variables must be final or effectively final; Swift closures can capture mutable variables, so lifetime and later mutation need deliberate thought.

Java: complete program

Main.java

import java.util.*;
import java.util.function.*;
public class Main {

  public static void main(String[] args) throws Exception {
    List<Boolean> flags = List.of(-2, 0, 5).stream().map(x -> x < 0).toList();
    System.out.println(flags.get(0) + " " + flags.get(1) + " " + flags.get(2));
  }
}

Swift: complete program

main.swift

import Foundation
let flags = [-2, 0, 5].map { $0 < 0 }
print(flags.map { String($0) }.joined(separator: " "))

A closure is behavior, not an automatically parallel operation. These map examples evaluate a transformation; they do not imply concurrent execution.

challenge icon

Challenge

Easy

Implement 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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Java Developers

Practice on your own: Swift playground