一尘不染

如何知道两个表情符号是否将显示为一个表情符号?

swift

表情符号of由2个unicodeScalars👍U + 1F44D,🏼U + 1F3FC组成。

如何将其标识为1个“显示的”表情符号,因为它将在iOS上显示为此类?


阅读 415

收藏
2020-07-07

共1个答案

一尘不染

Swift 4(Xcode 9)更新

从Swift 4开始,“表情符号序列”被视为单个字素簇(根据Unicode 9标准):

let s = "a👍🏼b👨‍❤️‍💋‍👨"
print(s.count) // 4

因此不再需要其他解决方法。


(Swift 3和更早版本的旧答案:)

一个可能的选择是枚举并计算字符串中的“组成字符序列”:

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

另一个选择是在给定索引下找到组成的字符序列的范围:

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字符(扩展的字素簇)的数量可以大于 或小于 组成的字符序列的数量。

2020-07-07