Swift Strings and Characters
Handle Unicode text without assuming every visible character is one byte.
How it works
String is a collection of Character values representing extended grapheme clusters. Unicode scalars and UTF-8 bytes are different views of that same text. String interpolation inserts an expression with backslash and parentheses. Indices belong to the particular collection and view.
Run this Swift example
Install the toolchain for your platform from Swift.org, then check swift --version. The reviewed portable baseline is Swift 6.4.2 in Swift 6 mode on Ubuntu 26.04 x86_64 through the PC’s existing WSL installation. These are real Linux executions, not claims of Windows-native or Apple-platform test results. Windows Swift has separate C++/SDK prerequisites in its official setup guide.
Save the complete source as strings-characters.swift in a new learning folder. On Linux/macOS compile with swiftc -swift-version 6 -parse-as-library strings-characters.swift -o lesson, then run ./lesson. On a configured Windows toolchain use an output such as lesson.exe and run .\lesson.exe. The parse-as-library option supports the explicit @main entry point used by these sources. Compile each ordinary lesson separately.
Bhylu has no Swift browser runner. The JavaScript/Python editors do not run these sources; Apache, PHP and MySQL are not required. Downloads are source text, never executable teaching endpoints.
Download the complete strings-characters.swift · Download all source files with hash checks
For the optional collection, save download-examples.mjs in a new folder and run node download-examples.mjs. A local preview uses node download-examples.mjs http://127.0.0.1:8000/examples/swift/. It refuses an existing bhylu-swift-examples folder and installs or executes no Swift automatically. Apple-only files remain separate Xcode learning examples, not a portable Swift package target.
Example
@main
struct Lesson {
static func main() {
let name = "Café"
print(name.count, name.unicodeScalars.count, name.utf8.count)
let room = "Cedar"
print("Room: \(room)")
}
}
Expected result
4 5 6 Room: Cedar
The accent combines with the preceding letter, so there are four Characters but five Unicode scalars. The scalar sequence occupies six UTF-8 bytes. These counts answer different questions; none alone guarantees a text label will fit a visual layout.
Primary references: The Swift Programming Language and Apple framework documentation. Use the selected platform’s current requirements. Fictional workshop examples do not establish production safety or deployment approval.