Menu
CoddyTech

Strings and Interpolation

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

C printf interprets a format string and expects matching argument types; %% writes a literal percent sign. Swift interpolation inserts a typed expression into a String using a backslash and parentheses. The resulting text can be returned or printed independently of its construction.

C text commonly uses a NUL-terminated char array whose capacity and mutability must be tracked by the programmer. A string literal must not be modified. Swift String has value semantics and manages storage, with let preventing mutation of a string value and var allowing supported updates.

C: complete program

main.c

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

int main(void) {
int percent = 40;
    printf("Downloaded %d%%\n", percent);
    return 0;
}

Swift: complete program

main.swift

import Foundation
let percent = 40
print("Downloaded \(percent)%")

A C char buffer offset counts bytes, while Swift String indices follow its text representation. Formatting a number does not settle Unicode traversal rules.

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