Strings and Interpolation
Lesson 6 of 48 in Coddy's Swift for C# Developers course.
C# interpolated strings begin with $ and insert expressions inside braces. Swift inserts an expression with \(...) inside an ordinary string literal. A Swift String is a value type, while C# string is an immutable reference type; replacing a variable does not mutate other aliases in either example. Swift strings are not integer-indexed arrays of UTF-16 units. The example formats a multiplication statement, leaving character traversal for the Unicode lesson. String interpolation produces text; it does not make an expression safe to use as a numeric value without parsing.
C#
Complete program file: Program.cs.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int side = 4;
Console.WriteLine($"{side} squared = {side * side}");
}
}Swift
Complete program file: main.swift.
let side = 4
print("\(side) squared = \(side * side)")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 C# 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