Swift 判断字符串的emoji表情
2019-12-22 本文已影响0人
见哥哥长高了
extension Character
extension Character {
//简单的emoji是一个标量 以emoji的形式呈现给用户
var isSimpleEmoji: Bool {
guard let firstProperties = unicodeScalars.first.properties else {
return false
}
return unicodeScalars.count == 1 && (firstProperties.isEmojiPresentation || firstProperties.generalCategory ==.otherSymbol)
}
//检测标量是否将合并到emoji中
var isCombineIntoEmoji: Bool{
return unicodeScalars.count > 1 && unicodeScalars.contains{$0.properties.isJoinControl || $0.properties.isVariationSelector}
}
//属否为emoji表情
var isEmoji: Bool {
return isSimpleEmoji || isCombineIntoEmoji
}
}
extension String
extension String {
//是否为单个emoji表情
var isSingleEmoji: Bool {
return count == 1 && containsEmoj
}
//是否包含emoji表情
var containsEmoji: Bool {
return contains{$0.isEmoji}
}
//只包含emoji表情
var containsOnlyEmoji: Bool {
return !isEmpty && !contains{!$0.isEmoji}
}
//提取emoji表情字符串
var emojiString: String {
return emojis.map{ String($0) }.reduce("",+)
}
//获取emoji表情数组
var emojis: [Character] {
return filter{$0.isEmoji}
}
//提取单元编码标量
var emojiScallars: [UnicodeScalar] {
return filter{$0.isEmoji}.flatMap{ $0.unicodeScalars}
}
}
使用举例
"A̛͚̖".containsEmoji // false
"3".containsEmoji // false
"A̛͚̖▶️".unicodeScalars // [65, 795, 858, 790, 9654, 65039]
"A̛͚̖▶️".emojiScalars // [9654, 65039]
"3️⃣".isSingleEmoji // true
"3️⃣".emojiScalars // [51, 65039, 8419]
"👌🏿".isSingleEmoji // true
"🙎🏼♂️".isSingleEmoji // true
"👨👩👧👧".isSingleEmoji // true
"👨👩👧👧".containsOnlyEmoji // true
"Hello 👨👩👧👧".containsOnlyEmoji // false
"Hello 👨👩👧👧".containsEmoji // true
"👫 Héllo 👨👩👧👧".emojiString // "👫👨👩👧👧"
"👨👩👧👧".count // 1
"👫 Héllœ 👨👩👧👧".emojiScalars // [128107, 128104, 8205, 128105, 8205, 128103, 8205, 128103]
"👫 Héllœ 👨👩👧👧".emojis // ["👫", "👨👩👧👧"]
"👫 Héllœ 👨👩👧👧".emojis.count // 2
"👫👨👩👧👧👨👨👦".isSingleEmoji // false
"👫👨👩👧👧👨👨👦".containsOnlyEmoji // true