Menu
CoddyTech

Unicode and Character Indices

Lesson 23 of 48 in Coddy's Swift for R Developers course.

For this valid Unicode string, R nchar with type = "chars" counts two characters in the code-point sense, while type = "bytes" on its UTF-8 form counts three bytes. Neither performs extended-grapheme segmentation. The decomposed and precomposed strings compare unequal here without explicit normalization.

Swift String iterates Character values, which are extended grapheme clusters. Its count is one for this accent, and equality recognizes canonical equivalence with the precomposed spelling. unicodeScalars and utf8 expose different views. String.Index advances through the selected view; integer offsets are not direct character subscripts.

Swift counts the combined accent as one Character and recognizes canonical equivalence, while its UTF-8 view still has three bytes. Text width, byte count, code-point count and grapheme count answer different questions. Select the unit required by the task before indexing or counting.

Complete R comparison program:

text <- "e\u0301"
cat(nchar(text, type = "chars"), "\n", sep = "")
cat(tolower(as.character(text == "é")), "\n", sep = "")
cat(nchar(enc2utf8(text), type = "bytes"), "\n", sep = "")

Complete Swift comparison program, compiled from these files:

main.swift

let text = "e\u{301}"
print(text.count)
print(text == "é")
print(text.utf8.count)
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 R Developers

Practice on your own: Swift playground