Menu
CoddyTech

Unicode and Character Indices

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

Luau strings contain bytes. For this decomposed accent, # counts three UTF-8 bytes and utf8.len counts two Unicode code points. String equality compares the byte sequence, so a precomposed accent is not equal without suitable normalization. Neither count segments extended grapheme clusters.

Swift String.count counts one Character here, while unicodeScalars.count is two. Swift equality recognizes canonical equivalence, so the two accent spellings compare equal. Use String.Index for character boundaries and select utf8 or unicodeScalars only when that unit matches the requirement. Byte positions cannot be reused as character indices.

Luau

Complete Luau console program:

main.luau

local text = "e\u{301}"
print(tostring(#text) .. " " .. tostring(utf8.len(text)))
print(text == "é")

Swift

Complete program; compile the listed files together:

main.swift

import Foundation
let text = "e\u{301}"
print(text.count, text.unicodeScalars.count)
print(text == "é")
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 Luau Developers

Practice on your own: Swift playground