Functions and Labels
Lesson 16 of 48 in Coddy's Swift for C Developers course.
C and Swift both support free functions, though C declarations and definitions are organized through translation units and headers. Swift sibling source files compile into one module, and these exercises place helpers in Functions.swift while main.swift calls them. Return types and parameter types remain explicit contracts.
C calls pass positional arguments without language-level external labels or default parameter values. Swift separates the caller label from the local parameter name, and an underscore suppresses a label. Its default count lets the caller omit an argument. The C comparison supplies count explicitly and prints directly; the Swift helper returns text for its caller.
C: complete program
main.c
#include <stdio.h>
static void line(char symbol, int count) { for (int i = 0; i < count; ++i) putchar(symbol); putchar('\n'); }
int main(void) { line('*', 3); return 0; }
Swift: complete program
Functions.swift
import Foundation
func line(_ symbol: String, count: Int = 3) -> String {
String(repeating: symbol, count: count)
}main.swift
import Foundation
print(line("*"))Preserve required external labels when implementing a Swift API. Parameter order alone does not fully describe the call syntax.
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 C 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