简体   繁体   English

如何将字符串元素与 Swift 中的 unicode 字符进行比较?

[英]How do I compare a string element to a unicode character in Swift?

I'm writing a code that will take in characters from the International Phonetic Alphabet and model them as phonemes to analyze phonologically.我正在编写一个代码,它将接收国际音标中的字符并将它们建模为音素以进行语音分析。 I need to be able to compare parts of a symbol (diacritics) to certain unicode characters.我需要能够将符号(变音符号)的一部分与某些 unicode 字符进行比较。 This is what I'm currently doing (what isn't working)这就是我目前正在做的事情(什么不起作用)

let diacritics : [String : String] = [
    ...
    "\u{2B0}" : "aspirated",
    ...
]

let elementsInSample = Array(sample)
for element in elementsInSample {
    if diacritics.keys.contains(String(element)) {
        \\Do things
    }
}

.contains will return false for ʰ when the key is in unicode.当键为 unicode 时,.contains 将为 ʰ 返回 false。 How do I rearrange the types so that it will be accurate?如何重新排列类型以使其准确?

You may want to work with Unicode Scalars, rather than Characters.您可能希望使用 Unicode 标量,而不是字符。

let diacritics : [Unicode.Scalar : String] = [
    //...
    "\u{2B0}" : "aspirated",
    //...
]

let sample = "ʰ"
for element in sample.unicodeScalars {
    if let value = diacritics[element] {
        print(value)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM