NSSpellChecker returning an out of bounds range

I was experimenting with NSSpellChecker on a macOS app with Swift and I noticed that when there are no spelling mistakes it returns an out of bounds range, specifically one with a lowerBound equals to the max value of a 64-bit signed integer.

Am I doing something wrong or is it a bug on Apple's part?

let sentence = "What a beautiful world."
let range = NSSpellChecker.shared.checkSpelling(of: sentence, startingAt: 0)
// "What a beautiful world." range: {9223372036854775807, 0}
// "What a beautiful worldk." range: {17, 6}
Answered by Developer Tools Engineer in 716467022

This is the same value as a Foundation constant called NSNotFound. Objective-C does not allow value types like NSRange to be nil, so by convention, Objective-C APIs that return NSRange set the range's location to NSNotFound in the situations where they would return nil in Swift.

The Range.init(_:in:) initializer you usually use to convert NSRange to Range<String.Index> correctly handles NSRange by returning nil when the NSRange’s location is NSNotFound, so if you write:

let sentence = "What a beautiful world."
let nsRange = NSSpellChecker.shared.checkSpelling(of: sentence, startingAt: 0)
let range = Range(nsRange, in: sentence)

The range constant should be nil for the first example sentence and a valid range for the second sentence.

That's the NSNotFound constant..

Accepted Answer

This is the same value as a Foundation constant called NSNotFound. Objective-C does not allow value types like NSRange to be nil, so by convention, Objective-C APIs that return NSRange set the range's location to NSNotFound in the situations where they would return nil in Swift.

The Range.init(_:in:) initializer you usually use to convert NSRange to Range<String.Index> correctly handles NSRange by returning nil when the NSRange’s location is NSNotFound, so if you write:

let sentence = "What a beautiful world."
let nsRange = NSSpellChecker.shared.checkSpelling(of: sentence, startingAt: 0)
let range = Range(nsRange, in: sentence)

The range constant should be nil for the first example sentence and a valid range for the second sentence.

NSSpellChecker returning an out of bounds range
 
 
Q