我有兩個帶有字串的陣列。
let exclude = ["text 1", "text 2", "APP", "John"]
let array2 = ["this is text 1", "This is text 2", "This App is under development", "John is working on this project", "This is great"]
我試圖過濾包含在 exclude from array2 中的任何文本,不區分大小寫。所以在這個例子中它應該列印"This is great"
而不是為每個過濾器使用多行,例如:
let filter = array2.filter{!$0.contains("APP")}
我試過:
var filter = array2.filter({exclude.contains($0)})
但它沒有過濾。任何建議將不勝感激
uj5u.com熱心網友回復:
使用“顯式”return而沒有$0.
let filtered = array2.filter { aString in
return !exclude.contains(where: { anExcludedString in
return aString.range(of: anExcludedString, options: .caseInsensitive) != nil
})
}
為什么var filter = array2.filter({exclude.contains($0)})不起作用?
第一個問題:
沒有不區分大小寫的檢查。第二個問題:
您使用的contains()是 a[String],而不是String. 所以它期望兩個字串之間完全相等。所以如果array2是["APP"],它會起作用。
例如,如果您有:
let exclude = ["text 1", "text 2", "APP", "John"]
let array2 = ["this is text 1", "This is text 2", "This App is under development", "John is working on this project", "This is great", "This APP is under development"]
let filtered = array2.filter { aString in
return !exclude.contains(where: { anExcludedString in
return aString.contains(anExcludedString)
})
}
然后"This APP is under development"就會被洗掉。
現在,回到最初的答案,檢查不區分大小寫的方法是使用range(of:options:).
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321554.html
