Strings and Interpolation
Lesson 6 of 48 in Coddy's Swift for PHP Developers course.
PHP double-quoted strings interpolate variables, and concatenation uses a dot. Complex expressions are often formatted or combined explicitly, as the arithmetic output here shows. PHP strings are byte sequences; str_starts_with checks the supplied prefix without treating it as a number.
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 print a completion percentage and check an ASCII filename prefix. Keep punctuation inside the intended string fragments, and use explicit conversion or interpolation when moving numbers into text. Formatting remains separate from the exercise's badge rules.
Complete PHP comparison program:
<?php
declare(strict_types=1);
$done = 3;
echo "progress=", $done * 25, "%\n";
echo str_starts_with("report.csv", "report") ? "true\n" : "false\n";
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 PHP 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