如何知道两个表情符号是否会显示为一个表情符号?
表情符号👍🏼由2个unicodeScalar👍U + 1F44D,🏼U + 1F3FC组成。
这怎么能被识别为1'显示'的表情符号,因为它会在iOS上显示?
Swift 4(Xcode 9)的更新
从Swift 4开始,一个“表情符号序列”被视为一个单一的字形集群(根据Unicode 9标准):
let s = "a👍🏼b👨❤️💋👨" print(s.count) // 4
所以其他解决方法不再需要了。
(Swift 3及更早的老答案:)
一个可能的select是枚举和计数string中的“组合字符序列”:
let s = "a👍🏼b👨❤️💋👨" var count = 0 s.enumerateSubstringsInRange(s.startIndex..<s.endIndex, options: .ByComposedCharacterSequences) { (char, _, _, _) in if let char = char { count += 1 } } print(count) // 4
另一种select是在给定索引处查找组合字符序列的范围:
let s = "👨❤️💋👨" if s.rangeOfComposedCharacterSequenceAtIndex(s.startIndex) == s.characters.indices { print("This is a single composed character") }
作为String
扩展方法:
// Swift 2.2: extension String { var composedCharacterCount: Int { var count = 0 enumerateSubstringsInRange(characters.indices, options: .ByComposedCharacterSequences) { (_, _, _, _) in count += 1 } return count } var isSingleComposedCharacter: Bool { return rangeOfComposedCharacterSequenceAtIndex(startIndex) == characters.indices } } // Swift 3: extension String { var composedCharacterCount: Int { var count = 0 enumerateSubstrings(in: startIndex..<endIndex, options: .byComposedCharacterSequences) { (_, _, _, _) in count += 1 } return count } var isSingleComposedCharacter: Bool { return rangeOfComposedCharacterSequence(at: startIndex) == startIndex..<endIndex } }
例子:
"👍🏼".composedCharacterCount // 1 "👍🏼".characters.count // 2 "👨❤️💋👨".composedCharacterCount // 1 "👨❤️💋👨".characters.count // 4 "🇩🇪🇨🇦".composedCharacterCount // 2 "🇩🇪🇨🇦".characters.count // 1
如您所见,Swift字符(扩展字形群集)的数量可以比构成字符序列的数量更多或更less 。