Menu
CoddyTech

Strings and Interpolation

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

R commonly constructs text with paste, paste0 or sprintf. Sprintf uses formatting placeholders and %% for a literal percent sign; quoted strings do not interpolate arbitrary expressions by themselves. Character vectors can contain multiple strings, so a text operation may return several results rather than one scalar.

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.

Both examples format one completion percentage and test an ASCII prefix. Cat writes the supplied values directly, while print would add R display conventions such as indices or quotes. Keep console formatting separate from the task's returned output string.

Complete R comparison program:

done <- 3L
cat(sprintf("progress=%d%%", done * 25L), "\n", sep = "")
cat(tolower(as.character(startsWith("report.csv", "report"))), "\n", sep = "")

Complete Swift comparison program, compiled from these files:

main.swift

let done = 3
print("progress=\(done * 25)%")
print("report.csv".hasPrefix("report"))
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 R Developers

Practice on your own: Swift playground