Menu
CoddyTech

Strings and Interpolation

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

JavaScript template literals interpolate expressions inside ${...} and create string values. Swift String interpolation uses a backslash followed by parentheses instead. Both examples construct a path, test its prefix and create a repeated marker, but the text traversal models differ beyond these ASCII operations.

JavaScript strings are immutable UTF-16 sequences, while Swift String has value semantics and provides Character-based operations. A Swift var can mutate its string value without changing a copied String. Interpolation formats a value as text; it is not numeric parsing or a guarantee about Unicode index units.

JavaScript

Complete JavaScript console program:

main.js

const folder = "cache";
const path = `${folder}/image`;
console.log(path.startsWith("cache/"));
console.log(".".repeat(3));

Swift

Complete program; compile the listed files together:

main.swift

import Foundation
let folder = "cache"
let path = "\(folder)/image"
print(path.hasPrefix("cache/"))
print(String(repeating: ".", count: 3))
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 JavaScript Developers

Practice on your own: Swift playground