Menu
CoddyTech

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 icon

Challenge

Easy

Implement 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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Dart Developers

Practice on your own: Swift playground