此post之后,我尝试将代码从Swift 2.0更新到Swift 5.0,以检查哪些表情符号具有可用的肤色以及是否已经存在其他变体。 我详细的更新代码:
extension String {
var emojiSkinToneModifiers: [String] {
return [ "?", "?", "?", "?", "?" ]
}
var emojiVisibleLength: Int {
var count = 0
enumerateSubstrings(in: startIndex..<endIndex, options: .byComposedCharacterSequences) { (_, _, _, _) in
count = count + 1
}
return count
}
var emojiUnmodified: String {
if self.count == 0 {
return ""
}
let range = String(self[..<self.index(self.startIndex, offsetBy: 1)])
return range
}
var canHaveSkinToneModifier: Bool {
if self.count == 0 {
return false
}
let modified = self.emojiUnmodified + self.emojiSkinToneModifiers[0]
return modified.emojiVisibleLength == 1
}
}
并与数组一起使用:
let emojis = [ "?", "??", "?" ]
for emoji in emojis {
if emoji.canHaveSkinToneModifier {
let unmodified = emoji.emojiUnmodified
print(emoji)
for modifier in emoji.emojiSkinToneModifiers {
print(unmodified + modifier)
}
} else {
print(emoji)
}
}
输出: ??????????? 为没有表情符号或没有表情符号的表情符号分配变体::?
我认为enumerateSubstringsInRange
是不正确的,并且self.characters.count
现在变得self.count
容易和正确地计算了一个表情符号(由组成)与before Swift 4相比,但在这种情况下可能没有用。我没看错吗?
谢谢
答案 0 :(得分:1)
“ hack”是比较正确表情符号(如“?”)和想要成为表情符号(如“??”)的视觉表示)。
我已经在这里和那里修改了您的代码以使其正常工作:
extension String {
static let emojiSkinToneModifiers: [String] = ["?", "?", "?", "?", "?"]
var emojiVisibleLength: Int {
var count = 0
let nsstr = self as NSString
let range = NSRange(location: 0, length: nsstr.length)
nsstr.enumerateSubstrings(in: range,
options: .byComposedCharacterSequences)
{ (_, _, _, _) in
count = count + 1
}
return count
}
var emojiUnmodified: String {
if isEmpty {
return self
}
let string = String(self.unicodeScalars.first!)
return string
}
private static let emojiReferenceSize: CGSize = {
let size = CGSize(width : CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
let rect = ("?" as NSString).boundingRect(with: size,
options: .usesLineFragmentOrigin,
context: nil)
return rect.size
}()
var canHaveSkinToneModifier: Bool {
if isEmpty {
return false
}
let modified = self.emojiUnmodified + String.emojiSkinToneModifiers[0]
let size = (modified as NSString)
.boundingRect(with: CGSize(width : CGFloat.greatestFiniteMagnitude,
height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
context: nil).size
return size == String.emojiReferenceSize
}
}
让我们尝试一下:
let emojis = [ "?", "??", "?" ]
for emoji in emojis {
if emoji.canHaveSkinToneModifier {
let unmodified = emoji.emojiUnmodified
print(unmodified)
for modifier in String.emojiSkinToneModifiers {
print(unmodified + modifier)
}
} else {
print(emoji)
}
print("\n")
}
瞧!
? ?? ?? ?? ?? ?? ? ?? ?? ?? ?? ?? ?