簡體   English   中英

Swift 將“字符”轉換為“Unicode.Scalar”

[英]Swift convert 'Character' to 'Unicode.Scalar'

我試圖從 String 中過濾出非字母字符,但遇到了CharacterSet使用Unicode.Scalar和 String 由Character組成的問題。

Xcode 給出了錯誤:

無法將“String.Element”(又名“Character”)類型的值轉換為指定類型“Unicode.Scalar”?

let name = "name"
let allowedCharacters = CharacterSet.alphanumerics
let filteredName = name.filter { (c) -> Bool in
    if let s: Unicode.Scalar = c { // cannot convert
        return !allowedCharacters.contains(s)
    }
    return true
}

CharacterSet有一個不幸的名字,它繼承自 Objective C。實際上,它是一組Unicode.Scalar ,而不是Characters (Unicode 術語中的“擴展Characters簇”)。 這是必要的,因為雖然有一組有限的 Unicode 標量,但有無限數量的可能的字素簇。 例如, e + ◌̄ + ◌̄ + ◌̄ ... ad e + ◌̄ + ◌̄ + ◌̄ ...仍然只是一個簇。 因此,不可能詳盡地列出所有可能的集群,並且通常不可能列出具有特定屬性的它們的子集。 問題中的集合操作必須改用標量(或至少使用從組件標量派生的定義)。

在 Swift 中, String有一個unicodeScalars屬性,用於在標量級別對字符串進行操作,並且該屬性是直接可變的。 這使您可以執行以下操作:

// Assuming...
var name: String = "..."

// ...then...
name.unicodeScalars.removeAll(where: { !CharacterSet.alphanumerics.contains($0) })

一個Character可以包含多個UnicodeScalar ,因此您需要遍歷所有UnicodeScalar ,並檢查它們是否包含在CharacterSet.alphanumerics

let allowedCharacters = CharacterSet.alphanumerics
let filteredName = name.filter { (c) -> Bool in
    return !c.unicodeScalars.contains(where: { !allowedCharacters.contains($0)})
}

測試輸入: let name = "asd😊1"

測試輸出: "asd1"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM