Test iOS Tokenization Ranges on a Cloud Mac
When the same studio builds English search for client A and Chinese word selection for client B, the most dangerous assumption to reuse is not the interface—it is the definition of “a word.” Splitting on spaces fails to handle Chinese, while passing character counts directly to a text control can select the wrong text after an emoji. Start by running a natural-language tokenization acceptance suite on a cloud Mac, checking linguistic boundaries separately from index conversion. Then bring the same fixtures into your iOS test target.
Define the tokenization output contract first
This article uses NLTokenizer from the system NaturalLanguage framework, with the unit set to .word. It is suitable for word selection and word-level search preprocessing. It is not a domain-specific dictionary, nor does it guarantee that proper names will always remain a single token. If a client’s brand names need special handling, define separate product rules.
Each result must include at least the original token text, its UTF-16 start offset, and its length. Offsets must refer to the same, unmodified string. Do not remove spaces or lowercase a copy and then apply its ranges to the original.
String.countcounts extended grapheme clusters, whileNSRangeuses UTF-16 units in common text APIs. These are not interchangeable, and ranges must not be stored separately from the original text that produced them.
Run the minimal acceptance suite in a dedicated directory
The cloud Mac needs working developer tools. First run xcrun --find swift to confirm that the compiler is available, then create a test directory dedicated to the project. Save the following code as TokenCheck.swift. It neither accesses client files nor downloads models.
import Foundation
import NaturalLanguage
struct Span: Codable {
let text: String
let location: Int
let length: Int
}
struct Record: Codable {
let input: String
let spans: [Span]
}
let fixtures = [
"Build cloud apps.",
"客户订单与远程构建",
"東京でSwiftを使う",
"클라우드 Mac 개발",
"Cafe\u{301} 👩🏽💻 search",
"",
" \n\t "
]
var records: [Record] = []
for input in fixtures {
let tokenizer = NLTokenizer(unit: .word)
tokenizer.string = input
let ranges = tokenizer.tokens(
for: input.startIndex..<input.endIndex
)
var previousEnd = input.startIndex
var spans: [Span] = []
for range in ranges {
precondition(range.lowerBound >= previousEnd)
precondition(range.lowerBound < range.upperBound)
let nsRange = NSRange(range, in: input)
guard let restored = Range(nsRange, in: input) else {
fatalError("Invalid UTF-16 range")
}
precondition(restored == range)
let token = String(input[range])
precondition(
(input as NSString).substring(with: nsRange) == token
)
spans.append(Span(
text: token,
location: nsRange.location,
length: nsRange.length
))
previousEnd = range.upperBound
}
if input == "Build cloud apps." {
precondition(spans.map(\.text) == ["Build", "cloud", "apps"])
}
if input.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
precondition(spans.isEmpty)
}
records.append(Record(input: input, spans: spans))
}
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data = try encoder.encode(records)
FileHandle.standardOutput.write(data)
Run the script and save the environment details:
set -eu
mkdir -p evidence
xcrun swift TokenCheck.swift > evidence/tokens.json
sw_vers > evidence/macos.txt
xcrun swift --version > evidence/swift.txt
A nonzero exit status must fail the acceptance check. The output files represent this test run; never substitute old files for the results of a failed run. When integrating this into a pipeline, assign a separate evidence directory to every run.
Separate contract violations from linguistic differences
The script checks for nonempty ranges, correct ordering, and UTF-16 round-trip consistency. These are strict contractual requirements. The short English sentence also has an explicit expected result to catch deviations in basic behavior. For Chinese, Japanese, and mixed-script fixtures, start by saving the results rather than hard-coding every token count.
Create separate fixtures for client vocabulary
Add the client’s frequently used product names, abbreviations, hyphenated words, and numbers with units. If the product requires a particular name to remain intact, assert that behavior at the product wrapper layer rather than assuming the system tokenizer already knows the rule. When the text’s language is known, you can call setLanguage, but automatic detection and an explicitly specified language should be tested as separate configurations.
If a system upgrade changes only word boundaries, review the semantics manually first. Out-of-bounds ranges, mismatched text fragments, or an error exit must fail immediately. Do not accept both categories of change with a single “update snapshots” action.
Check ranges again before passing them to the UI
The round-trip checks above validate the conversion method; they do not prove that the UI integration is correct. The next layer of tests should call the application’s actual range adapter and verify that it does not treat location as a Swift character offset.
Add three groups of integration cases: an emoji before the target word; the same word appearing more than once in a sentence; and a user editing earlier text after tokenization. The first two expose offset-conversion errors or incorrect searches. The third must invalidate the old results and trigger tokenization again.
Do not recover positions by searching the entire string for each token with range(of:): repeated words will resolve to their first occurrence. Do not concatenate every token and compare the result with the original text either. Spaces and some punctuation may legitimately be absent from word-level output.
Rerun on the target OS and save a baseline
A Mac script makes it easy to validate shared logic quickly, but you cannot assume that macOS and iOS produce identical language-processing results. Add the fixtures and range adapter to the iOS test target, retain the same invariant checks, and add the word-boundary assertions required by the client.
Release records should capture the commit ID, OS version, language-hint configuration, fixture text, and output ranges together. When a test fails, first reproduce it with the shortest possible input. Then determine whether the cause is a change in system word boundaries, modified source text, or an application conversion error. Maintain separate vocabulary fixtures for each client so that one client’s special rules do not silently change another client’s search behavior.
The final acceptance criterion is not “it produced lots of words.” Every returned range must recover the correct fragment from the correct version of the source text, required word boundaries must have explicit evidence, and system changes must be traceable and explainable.
Frequently asked questions
Does passing on macOS guarantee identical iOS tokenization?
No. The Mac script checks input and range contracts quickly. Run the same fixtures on the target iOS runtime before release and record results separately.
Should every fixture assert an exact token count?
No. Shared checks should enforce valid, ordered ranges and UTF-16 round trips. Product-specific word boundaries need separate, versioned semantic expectations.
Set up a Mac for your next client project
Rent a dedicated physical Mac mini by the day, week, month or quarter. Your Mac is ready on the day you order. Track progress in the console, and submit a support ticket there if you need help.
Rent a cloud Mac