Unicode and Character Indices
Lesson 23 of 48 in Coddy's Swift for Dart Developers course.
Dart String.length counts UTF-16 code units. Iterating runes yields Unicode code points; neither measure is a count of user-perceived characters. Swift String.count counts extended grapheme clusters, represented by Character. A base letter followed by a combining accent can form one Swift character even though it contains two Unicode scalars. Dart string equality compares code-unit sequences, while Swift string equality recognizes canonical equivalence. Swift indices are String.Index values, not integer offsets. Use index(after:) to advance one character. No third-party grapheme package is needed for the Swift operation shown here.
Complete Dart program. Each labelled block is a separate file.
main.dart
void main() {
final text = 'é!';
print(text.length);
print(text.runes.length);
print('é' == 'é');
}Complete Swift program. Each labelled block is a separate file.
main.swift
import Foundation
let text = "é!"
print(text.count)
print(text.unicodeScalars.count)
print("é" == "é")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 Dart 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