Functions and Labels
Lesson 16 of 48 in Coddy's Swift for Lua Developers course.
Lua calls normally pass positional arguments. A table argument can simulate named options, but it is a table value interpreted by the function, not a language-level argument-label declaration. Missing positional arguments become nil, and extra arguments may be ignored unless the function accepts them.
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.
Both functions repeat the supplied sound. Lua string.rep and Swift String(repeating:count:) provide the operation directly. Read the required Swift signature exactly when implementing a task: a correct calculation with the wrong labels is still a different API.
Complete Lua comparison program:
local function echo(sound, times)
return string.rep(sound, times)
end
print(echo("ha", 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 Lua 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