Menu
CoddyTech

Strings and Interpolation

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

Kotlin string templates use a dollar prefix; Swift interpolation uses a backslash and parentheses inside the literal. Swift String is a value type containing Unicode text. You can concatenate strings, test prefixes, and iterate over Characters without converting to a byte array. The example checks a prefix and constructs a repeated word rather than indexing text numerically. Kotlin String indexing uses UTF-16 code units, so porting an indexed loop requires more thought than changing method names. Swift provides separate views for UTF-8, UTF-16, and Unicode scalars. Choose a view only when the operation is defined in those units; ordinary text iteration uses Character.

Kotlin

fun main() {
    val word = "echo"
    println(word.startsWith("ec"))
    println(word.repeat(2))
}

Swift

let word = "echo"
print(word.hasPrefix("ec"))
print(String(repeating: word, count: 2))
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 Kotlin Developers

Practice on your own: Swift playground