Menu
CoddyTech

Unicode and Character Indices

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

C# string.Length counts UTF-16 code units, and a C# char holds one such unit. A supplementary scalar needs a surrogate pair; a visible character can also contain several Unicode scalars. Swift String.count counts extended grapheme clusters represented by Character, not UTF-16 units or scalars. The example contains an e plus a combining acute accent followed by an emoji: two Swift Characters but four UTF-16 code units. Swift indices are String.Index values, not integer offsets. Canonically equivalent Characters compare equal. Normalization and grapheme segmentation are different concepts; counting scalars does not recover user-perceived character boundaries.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string text = "é😀";
        Console.WriteLine(text.Length);
        Console.WriteLine(char.IsHighSurrogate(text[2]) ? "high-surrogate" : "other");
    }
}

Swift

Complete program file: main.swift.

let text = "é😀"
print(text.count)
print(text.utf16.count)
let next = text.index(after: text.startIndex)
print(text[next])
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