最優雅的解決辦法應該使用較少知名的String.CompareOptions
結合.range(of:, options:)
。這允許您以較少的努力執行復雜的操作,例如匹配忽略特殊字符,而不僅僅是案例和使用正則表達式(這對於您的特定目的會很有利)。如果你不知道它們是什麼,我建議你看看它。
返回專題: 您可以閱讀更多關於String.CompareOptions
here。該文檔適用於NSString
,但這些文檔也適用於String
。
你會再使用它,如下所示:
let userInput = "HeLLö, how are you doing? Greetings!"
let acceptedWords = ["hello", "hi", "greeting"]
var resultCommants = acceptedWords.filter { (word) -> Bool in
return userInput.range(of: word, options: [.caseInsensitive, .diacriticInsensitive]) != nil
}
// resultCommands = ["hello", "greeting"]
正如你所看到的,HeLLö
比賽hello
和Greetings
因爲greeting
.caseInsensitive
和.diacriticInsensitive
匹配。
如果您不熟悉.filter
運算符,它會遍歷您的數組,並且對於每個項目word
,都希望您返回true或false,具體取決於項目是否應包含在您的過濾版本中陣列。這通過比較.range(of:, options:)
與nil
的結果來完成。不等號nil
表示找到該單詞,如果不是,則等於零。你當然可以使用該範圍,如果你想知道其中這個詞被發現。
'switch text.lowercased()'並在'switch'語句的不同情況下輸入小寫字符串。請注意,某些特殊字符在應用'lowercased()'或'uppercased()'時不會像預期的那樣翻譯:請參閱以下問答內容(http://stackoverflow.com/questions/30532728)/how-to-compare-two-strings-ignored-case-in-swift-language)(特別是對問題的評論)。 – dfri