Menu
CoddyTech

Strings and Interpolation

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

Ruby double-quoted strings interpolate expressions with #{...}. Methods such as start_with? answer text questions directly, and multiplying a string by an integer repeats it. Ruby strings can be mutable objects with an encoding, so object sharing and character interpretation need separate attention when porting.

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 target uses Swift interpolation and hasPrefix for the same ASCII formatting example. A Swift String is a value type, so mutating a copied value does not mutate another copy. Keep exact spaces and punctuation separate from the exercise's own badge-field rules.

Complete Ruby comparison program:

done = 3
puts "progress=#{done * 25}%"
puts "report.csv".start_with?("report")

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

Practice on your own: Swift playground