Determining String text direction

What is the recommended way currently to determine the text direction of a range of a String?

Unicode Enthusiasts Unite proposes an extension for Unicode Scalar Bidirectional Class Values.

I do not think you can reliably determine the direction(s) of a slice without being able to inspect the entire string according to the Bidirectional Algorithm. It does not appear that the necessary properties are exposed by Unicode.Scalar.Properties or CharacterSet in Swift, so I think an implementation (or any “good enough” simplification) would need to fish the properties from the Unicode Character Database.

2 Likes

What does it mean for a slice/range to have direction?

1 Like

In the function I'm looking at now, I have a Range<String.Index> representing a selected portion of a String, and need to decide what the left and right arrow keys do to the selection. (This is in a mathematical formula editor; there is no NS/UITextView/SwiftUI TextField.) In the simple cases, if all the selected text is left-to-right, then the new selection becomes range.lowerBound ..< range.lowerBound and if all the text is right-to-left, then the new selections becomes range.upperBound ..< range.upperBound Similarly, should it use str.index(before:) or str.index(after:) to move the selection one character to the right or left? (The old C++ code doesn't behave well with mixed bidirectional text, so I'm not worrying about that yet.)

Here is a good introduction to what we mean by the “direction” of a string or slice thereof.

1 Like