I have an array of strings in Swift. I also have an url and I want to check if this url contains one of the elements contained into this array of strings I have.
So if url.pathComponents.contains("how can I do that?")
I thought at for loop but I was looking at a one line solution if any.
Thanks a lots.
CodePudding user response:
let things = ["aaa", "bbb", "ccc"]
url.pathComponents.contains(where: things.contains)
For example:
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
To break that down a bit: if you have an array, things, then things.contains is a function that given a thing will return true if it is in things. And such a function is useful as the predicate function for contains(where:), which is a function on collections that will return true if any of the things in the collection satisfy the given predicate function.
Or you could write the predicate as a closure expression like { thing in things.contains(thing) }
.