Functions and Labels
Lesson 16 of 48 in Coddy's Swift for Python Developers course.
Python callers can pass arguments by parameter name unless a signature restricts them. Swift separates the external argument label used by callers from the internal parameter name. By default these names match; an underscore suppresses an external label.
Swift parameters declare types, and a return type follows ->. Function parameters are immutable local bindings. A function body uses return to send back a result; printing is a separate side effect. Top-level functions in separate files are visible in the same compiled module.
The example repeats a sound a specified number of times. Its call makes the label distinction visible. Preserve the task signature exactly: callers and the locked driver rely on those external labels.
Complete Python comparison program:
def echo(sound, times):
return sound * times
print(echo("ha", times=3))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
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Python 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 RulesPractice on your own: Swift playground