Menu
CoddyTech

Unicode and Character Indices

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

C strlen counts bytes before the first NUL, not Unicode characters. This source spells explicit UTF-8 bytes for a decomposed accented letter followed by an emoji, giving seven bytes. A char indexing operation reads one byte; the C standard does not make it an automatic Unicode scalar decoder.

Swift String.count counts Character values, which are extended grapheme clusters. Its UTF-16 view counts code units, so the target reports two Characters and four UTF-16 units. Use String.Index to move through valid String positions instead of treating integer offsets as character indices.

Swift String equality recognizes canonical equivalence, while C strcmp compares the byte sequence and performs no Unicode normalization. Thus precomposed and decomposed accents differ in the source and compare equal in Swift. Normalization and grapheme segmentation answer different questions.

C: complete program

main.c

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

int main(void) {
const char text[] = "e\xCC\x81\xF0\x9F\x98\x80";
    printf("%zu\n", strlen(text));
    puts(strcmp("\xC3\xA9", "e\xCC\x81") == 0 ? "true" : "false");
    return 0;
}

Swift: complete program

main.swift

import Foundation
let text = "e\u{301}😀"
print("\(text.count) \(text.utf16.count)")
print("é" == "e\u{301}")

The source UTF-8 bytes are explicit, avoiding assumptions about the compiler source encoding. Byte counts, scalar counts and grapheme counts are distinct contracts.

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 C Developers

Practice on your own: Swift playground