Menu
CoddyTech

Functions and Labels

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

PHP supports named arguments using the declared parameter names, so changing a public parameter name can affect callers. Positional arguments may precede named ones. A Swift external label has a similar readability role but can differ from the local parameter name used inside the implementation.

Swift distinguishes argument labels used by callers from parameter names used inside the function. An underscore omits a label. The signature here accepts echo("ha", times: 3), but uses count inside its body. Static checking verifies the required call shape and value types.

PHP uses times as the parameter name and call label. Swift uses times externally and count internally, with an underscore suppressing the first label. Preserve the task's exact labels, because the locked driver calls that API rather than a merely equivalent function.

Complete PHP comparison program:

<?php
declare(strict_types=1);
function echo_sound(string $sound, int $times): string {
    return str_repeat($sound, $times);
}
echo echo_sound("ha", times: 3), "\n";

Complete Swift comparison program, compiled from these files:

Functions.swift

func echo(_ sound: String, times count: Int) -> String {
    return String(repeating: sound, count: count)
}

main.swift

print(echo("ha", times: 3))
challenge icon

Challenge

Easy

Implement perimeter(width:height:) for a rectangle. Input is width and height, each 1 through 1000. Output twice their sum. Preserve the external argument labels.

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 perimeter(width: 9, height: 4) == 26 && perimeter(width: 1, height: 7) == 16
}
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