Find The Writing Direction Of A String

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
}

Leave a Reply