Menu
CoddyTech

Strings and Interpolation

Lesson 6 of 48 in Coddy's Swift for C++ Developers course.

C++ can build formatted text with streams, concatenation or a formatting library, while Swift directly interpolates expressions inside String using a backslash and parentheses. std::string has value semantics and mutable character storage; copying it does not normally create a second reference to the same mutable string object. Swift String also has value semantics but exposes Character-based traversal rather than indexing bytes with integers. The displayed arithmetic is small and representable in both languages. Producing formatted text is separate from parsing or validating numeric input, and a formatted example does not establish Unicode indexing behavior.

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>

int main() {
int side = 4;
    std::cout << side << " squared = " << side * side << '\n';
}

Swift

Complete program file: main.swift.

let side = 4
print("\(side) squared = \(side * side)")
challenge icon

Challenge

Easy

Implement badge(_:team:). Input is two ASCII words of 1 to 20 letters: first name then team. Output the team in square brackets, one space, then the name.

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 badge("Ivo", team: "Oak") == "[Oak] Ivo" && badge("Lee", team: "Pine") == "[Pine] Lee"
}
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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for C++ Developers

Practice on your own: Swift playground