Functions and Labels
Lesson 16 of 48 in Coddy's Swift for C++ Developers course.
C++ and Swift both support free functions and default arguments, but ordinary C++ calls do not use Swift external argument labels. Swift distinguishes the label at the call site from the parameter name within the function; an underscore suppresses that external label. Parameters are constant bindings in a Swift function unless an explicit local copy or inout contract changes the design. The examples return text joined with separators, and printing remains the caller responsibility. A matching parameter order alone does not implement the full Swift callable interface when a required label such as times is present.
C++
Complete program file: main.cpp.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
std::string repeat_text(const std::string &text, int times) {
std::string result;
for (int i = 0; i < times; ++i) { if (i) result += "/"; result += text; }
return result;
}
int main() {
std::cout << repeat_text("ha", 3) << '\n';
}
Swift
Complete program file: Functions.swift.
func repeatText(_ text: String, times: Int) -> String {
return Array(repeating: text, count: times).joined(separator: "/")
}Complete program file: main.swift.
print(repeatText("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 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