Swift - 检查是否 url.pathComponents.contains 一个元素进入字符串数组

Swift - Check if url.pathComponents.contains one element into an array of strings

我在 Swift 中有一个字符串数组。我还有一个 url,我想检查这个 url 是否包含我拥有的这个字符串数组中包含的元素之一。

所以如果 url.pathComponents.contains(“我该怎么做?”)

我考虑过 for 循环,但我正在寻找单行解决方案(如果有的话)。

非常感谢。

let things = ["aaa", "bbb", "ccc"]
url.pathComponents.contains(where: things.contains)

例如:

let url = URL(string: "https://www.example.com/foo/bar/baz")!

let things = ["aaa", "bbb", "ccc"]
let doesnt = url.pathComponents.contains(where: things.contains) // false

let things2 = ["aaa", "bar", "ccc"]
let does = url.pathComponents.contains(where: things2.contains) // true

稍微分解一下:如果你有一个数组,things,那么 things.contains 是一个函数,如果它在 things 中,给定的东西将 return 为真。并且这样的函数作为 contains(where:) 的谓词函数很有用,它是一个集合函数,如果集合中的任何事物满足给定的谓词函数,它将 return 为真。 或者您可以将谓词写成闭包表达式,例如 { thing in things.contains(thing) }.