Menu
CoddyTech

Closures and Transformations

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

PHP arrow functions provide a short expression callback and capture outer variables by value. Traditional closures can explicitly capture by value or reference with use. Capturing an object by value still captures its object handle, so this distinction is not a general deep-copy guarantee.

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 transform the distances in order without changing the original collection. PHP array_map and Swift map produce result collections, but their key and collection conventions differ for richer inputs. Keep the transformation pure unless shared-state changes are a deliberate API requirement.

Complete PHP comparison program:

<?php
declare(strict_types=1);
$distances = [2, 5, 3];
$squares = array_map(fn(int $distance): int => $distance * $distance, $distances);
echo implode(" ", $squares), "\n";

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

Practice on your own: Swift playground