Menu
CoddyTech

Closures and Transformations

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

Python lambdas and Swift closures can be passed as values. Python comprehensions are often translated into operations such as map, filter, and reduce. Choose the operation based on whether you transform, retain, or combine elements.

A Swift closure can name parameters before in or use shorthand names such as $0. A final closure argument may be written after the parentheses. Captured mutable variables can carry state, so a closure is not necessarily a pure calculation. A closure stored beyond the function call may need an @escaping parameter declaration.

This example maps distances to their squares. It preserves the number and order of elements. The task instead retains selected strings and orders them, so consider each operation separately.

Complete Python comparison program:

distances = [2, 5, 3]
squares = list(map(lambda distance: distance * distance, distances))
print(" ".join(map(str, squares)))

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 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 Python Developers

Practice on your own: Swift playground