Looking at questions about how to do this in other languages (for example, this accepted answer for Ruby), it seems like a common technique is to determine if a string falls into the CJK range. The ruby response can be adapted to Swift strings as an extension using the following code:
extension String { var containsChineseCharacters: Bool { return self.unicodeScalars.contains { scalar in let cjkRanges: [ClosedInterval<UInt32>] = [ 0x4E00...0x9FFF, // main block 0x3400...0x4DBF, // extended block A 0x20000...0x2A6DF, // extended block B 0x2A700...0x2B73F, // extended block C ] return cjkRanges.contains { $0.contains(scalar.value) } } } } // true: "Hi! 大家好!It contains Chinese!".containsChineseCharacters // false: "Hello, world!".containsChineseCharacters
Ranges may already exist in the Foundation somewhere, rather than manually hard-coded them.
Above for Swift 2.0, for earlier use you will need to use the free contains function, not the protocol extension (twice):
extension String { var containsChineseCharacters: Bool { return contains(self.unicodeScalars) { // older version of compiler seems to need extra help with type inference (scalar: UnicodeScalar)->Bool in let cjkRanges: [ClosedInterval<UInt32>] = [ 0x4E00...0x9FFF, // main block 0x3400...0x4DBF, // extended block A 0x20000...0x2A6DF, // extended block B 0x2A700...0x2B73F, // extended block C ] return contains(cjkRanges) { $0.contains(scalar.value) } } } }
source share