Unicode and Character Indices
Lesson 23 of 48 in Coddy's Swift for Rust Developers course.
Rust str::len counts UTF-8 bytes, chars iterates Unicode scalar values, and encode_utf16 exposes UTF-16 code units. The decomposed accent has three bytes, two scalars and two UTF-16 units. Standard-library scalar iteration does not segment extended grapheme clusters. Swift String.count counts one Character for this text, while unicodeScalars and utf16 each count two. Swift also recognizes canonical equivalence in string equality, whereas Rust string equality compares the encoded text without automatic normalization. Neither language permits arbitrary integer character subscripts as a universal text operation: Rust byte slicing requires UTF-8 boundaries, and Swift Character navigation uses String.Index.
Rust
fn main() {
let text = "e\u{301}";
println!("{}", text.len());
println!("{}", text.chars().count());
println!("{}", text.encode_utf16().count());
}
Swift
let text = "é"
print(text.count)
print(text.unicodeScalars.count)
print(text.utf16.count)Challenge
EasyImplement uniqueCharacters(_:) using Swift Character equality: count distinct extended grapheme clusters. Input is one line of at most 50 Characters without line breaks. It may include composed accents or emoji. Output the count. Canonically equivalent Characters compare equal.
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 uniqueCharacters("🇨🇦🇨🇦x") == 2 && uniqueCharacters("éé") == 1 && uniqueCharacters("") == 0
}
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 Rust 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 Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog MergePractice on your own: Swift playground