Menu
CoddyTech

Strings and Interpolation

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

GDScript percent formatting combines a format string with values, and %% emits a literal percent sign. Swift interpolation uses a backslash followed by a parenthesized expression inside a String. Both construct text, while begins_with and hasPrefix answer a prefix question without numeric parsing.

GDScript String values and Swift String values preserve independent observable text under assignment. That differs from GDScript Array or Dictionary reference sharing. A Swift let String cannot be mutated, while var allows supported changes. Interpolation can format a numeric expression without turning the result back into a number.

These examples format a completion percentage and check an ASCII filename prefix. Preserve punctuation and spaces exactly when the caller expects a particular output format.

Complete GDScript comparison program:

extends SceneTree

func _init():
    var done = 3
    print("progress=%d%%" % (done * 25))
    print("report.csv".begins_with("report"))
    quit()

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 GDScript Developers

Practice on your own: Swift playground