Ookey Ookey - 4 months ago 24
Swift Question

Check if string latin or cyrillic

Is it some way to check if some string latin or cyrillic? I've tried

localizedCompare
String method, but it don't gave me needed result.

Answer

What about something like this?

extension String {
    var isLatin: Bool {
        let upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        let lower = "abcdefghijklmnopqrstuvwxyz"

        for c in self.characters.map({ String($0) }) {
            if !upper.containsString(c) && !lower.containsString(c) {
                return false
            }
        }

        return true
    }

    var isCyrillic: Bool {
        let upper = "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЮЯ"
        let lower = "абвгдежзийклмнопрстуфхцчшщьюя"

        for c in self.characters.map({ String($0) }) {
            if !upper.containsString(c) && !lower.containsString(c) {
                return false
            }
        }

        return true
    }

    var isBothLatinAndCyrillic: Bool {
        return self.isLatin && self.isCyrillic
    }
}

Usage:

let s = "Hi there"
if s.isLatin && !s.isBothLatinAndCyrillic {
    // String is latin
} else if s.isCyrillic && !s.isBothLatinAndCyrillic {
    // String is cyrillic
} else if s.isBothLatinAndCyrillic {
    // String can be either latin or cyrillic
} else {
    // String is not latin nor cyrillic
}

Considere there are cases where the given string could be both, for example the string:

let s = "A"

Can be both latin or cyrillic. So that's why there's the function "is both".

And it can also be none of them:

let s = "*"
Comments