Strings and Interpolation
Lesson 6 of 48 in Coddy's Swift for Lua Developers course.
Lua builds formatted strings with string.format or concatenation using the two-dot operator. The formatting call here uses a numeric placeholder and %% for a literal percent sign. Standard Lua has no built-in interpolation syntax that evaluates expressions inside a quoted string.
Swift interpolation places an expression inside \(...). String(number) explicitly converts a number, and + concatenates strings. A mutable Swift String can change its value while a copied string keeps its own value. Methods such as hasPrefix express a text predicate directly.
The Lua prefix check uses one-based byte positions on an ASCII filename. Swift hasPrefix avoids computing those positions. The progress example teaches formatting independently of the badge fields in the exercise; preserve the exact punctuation and spaces required by each output contract.
Complete Lua comparison program:
local done = 3
print(string.format("progress=%d%%", done * 25))
print(string.sub("report.csv", 1, 6) == "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 Lua 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