Quantcast
Channel: Yonat Sharon – Yonat Sharon – Programming Notes
Viewing all articles
Browse latest Browse all 23

Find The Writing Direction Of A String

$
0
0

When you need to know if a string is right-to-left (rtl) or left-to-right (ltr) – don’t check individual characters. Instead, use the Natural Language framework, available since iOS 12 and macOS 10.14:

import NaturalLanguage

extension String {
    var isRightToLeft: Bool {
        guard let language = NLLanguageRecognizer.dominantLanguage(for: self) else { return false }
        switch language {
        case .arabic, .hebrew, .persian, .urdu:
            return true
        default:
            return false
        }
    }
}

Then just use it like this:

if "שלום and سلام".isRightToLeft {
    // do what needs to be done
}

Viewing all articles
Browse latest Browse all 23

Latest Images

Trending Articles





Latest Images