Menu
CoddyTech

Strings and Interpolation

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

Java builds a string with + or a formatting API. Swift string interpolation inserts an expression using \(expression) inside a string literal. The expression is evaluated and rendered at that location.

Both examples describe a download progress reading, combining an integer and literal punctuation. Swift String is a value type. A let string cannot be appended to; a var string can. Java String objects are immutable even when the variable referring to one can be reassigned.

Java: complete program

Main.java

import java.util.*;
import java.util.function.*;
public class Main {

  public static void main(String[] args) throws Exception {
    int percent = 40;
    System.out.println("Downloaded " + percent + "%");
  }
}

Swift: complete program

main.swift

import Foundation
let percent = 40
print("Downloaded \(percent)%")

Do not read Swift string indices as Java integer offsets. This example only interpolates values; text traversal later uses Swift Character boundaries.

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

Practice on your own: Swift playground