Menu
CoddyTech

Unicode and Character Indices

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

Go strings are byte sequences; len counts bytes and range or utf8 decoding exposes runes. A rune is a Unicode code point, not necessarily a visible character. The decomposed accent and emoji here occupy seven UTF-8 bytes and three runes.

Swift String.count counts extended grapheme clusters represented by Character, so it reports two Characters. Its UTF-16 view reports four code units. String.Index follows valid text positions rather than being an arbitrary byte or rune offset.

Go string equality compares byte sequences and does not automatically normalize canonically equivalent accents. Swift String equality recognizes canonical equivalence. Normalization and grapheme segmentation address separate questions and neither can be replaced by counting encoding units.

Go: complete program

main.go

package main
import (
    "fmt"
    "unicode/utf8"
)

func main() {
text := "e\u0301😀"
    fmt.Println(len(text), utf8.RuneCountInString(text))
    fmt.Println("é" == "e\u0301")
}

Swift: complete program

main.swift

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

Choose bytes, runes or graphemes from the actual text contract. The same displayed text can have different valid counts under those representations.

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

Practice on your own: Swift playground