Strings and Interpolation
Lesson 6 of 48 in Coddy's Swift for Rust Developers course.
Rust str is UTF-8 text and String owns a growable UTF-8 buffer. Methods such as starts_with and repeat express text operations without manual indexing, and format! constructs formatted strings. Swift uses String values, hasPrefix and String(repeating:count:), with interpolation written as \(...). Swift String iteration yields Character grapheme clusters, while Rust chars yields Unicode scalar values; neither should be confused with a byte index. The ASCII word makes this formatting comparison simple, but later Unicode examples expose the different units. Choose an owned Rust clone or a borrow deliberately in source code, while ordinary Swift String assignment preserves value semantics.
Rust
fn main() {
let word = "echo";
println!("{}", word.starts_with("ec"));
println!("{}", word.repeat(2));
}
Swift
let word = "echo"
print(word.hasPrefix("ec"))
print(String(repeating: word, count: 2))Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Rust 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