从另一个数组的内容中过滤数组



我有 2 个数组,都带有字符串。

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"]

我试图过滤 array2 排除中包含的任何文本,不区分大小写。 所以在这个例子中,它应该打印"This is great"

而不是为每个过滤器使用多行,例如:let filter = array2.filter{!$0.contains("APP")}

我试过了:var filter = array2.filter({exclude.contains($0)})但它不会过滤。 任何建议将不胜感激

带有"显式"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)})不起作用?

  • 第一个问题:
    没有不区分大小写的检查。

  • 第二个问题:
    您在[String]上使用contains(),而不是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:)

相关内容

  • 没有找到相关文章

最新更新