Unicode and Character Indices
Lesson 23 of 48 in Coddy's Swift for Java Developers course.
Java String.length counts UTF-16 code units, and charAt returns one code unit. A supplementary Unicode code point needs a surrogate pair. Java codePointCount counts Unicode code points, which still need not match user-perceived characters.
Swift String.count counts Character values, each an extended grapheme cluster. The examples use a decomposed accented letter and a supplementary emoji: Java sees four UTF-16 code units and three code points; Swift sees two Characters. String.Index follows valid string positions, so advance from startIndex rather than treating an integer as an index.
Swift Character equality recognizes canonical equivalence, so precomposed and decomposed versions of the accented letter compare equal. Java String.equals compares the UTF-16 sequence and does not normalize it. Normalization and grapheme segmentation answer different questions; neither Java code-point counting nor UTF-16 length is a replacement for Swift Character counting.
Java: complete program
Main.java
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) throws Exception {
String text = "e\u0301\uD83D\uDE00";
System.out.println(text.length() + " " + text.codePointCount(0, text.length()));
System.out.println("\u00E9".equals("e\u0301"));
}
}Swift: complete program
main.swift
import Foundation
let text = "e\u{301}😀"
print("\(text.count) \(text.utf16.count)")
print("é" == "e\u{301}")An extended grapheme cluster may contain several code points, including combining marks or joined emoji. Avoid calling a Java char a Unicode character without specifying the code-unit meaning.
Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Java Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules5Collection Tools
Dictionaries and Missing KeysSets and MembershipUnicode and Character IndicesClosures and TransformationsRecap: Catalog MergePractice on your own: Swift playground