Functions and Labels
Lesson 16 of 48 in Coddy's Swift for GDScript Developers course.
GDScript functions use positional calls and may declare parameter types and defaults. Swift also supports defaults, but external argument labels are part of its callable interface. A separate local parameter name can be used inside the body, as times count does in the target.
An underscore removes the external label for one parameter. A Swift function signature includes its return type after an arrow, and returning String does not print it. Keep the caller output separate from the helper contract when the locked driver handles printing.
Both functions repeat a sound three times. The source supplies two positional arguments; the target call explicitly uses the required times label.
Complete GDScript comparison program:
extends SceneTree
func echo(sound: String, count: int) -> String:
return sound.repeat(count)
func _init():
print(echo("ha", 3))
quit()
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 GDScript 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