Strings and Interpolation
Lesson 6 of 48 in Coddy's Swift for Python Developers course.
Python f-strings embed expressions inside braces. Swift interpolation puts an expression inside \(...). Both construct a new string. Swift joins strings with +, and methods such as hasPrefix answer text questions without converting the text to a number.
Python strings are immutable objects. Swift strings have value semantics: a mutable binding can replace or mutate its string value, but a copy has its own observable value. Use String(number) to request a textual conversion explicitly. Interpolation can also insert a numeric expression into surrounding text.
This example formats a completion percentage and tests a filename prefix. It is separate from arranging the task badge fields. Keep punctuation and spaces inside the intended string literals because output matching is exact.
Complete Python comparison program:
done = 3
print(f"progress={done * 25}%")
print("report.csv".startswith("report"))Complete Swift comparison program, compiled from these files:
main.swift
let done = 3
print("progress=\(done * 25)%")
print("report.csv".hasPrefix("report"))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 Python 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