I want to test if the given array contains at least one object that contains a specific 'string' in it. Is it useful and possible?
Asked
Active
Viewed 393 times
3 Answers
1
Try filter()
.
struct S { let string: String }
let array = [ S(string: "a"), S(string: "b") ]
let hasAtleastOneA = array.filter({ $0.string == "a" }).count > 0

Avi
- 7,469
- 2
- 21
- 22
-
-
1There's nothing wrong with doing that in _any_ code. If you have a large array and expect the element near the beginning, you might want an approach that lets your bail early, but otherwise, this works everywhere. – Avi May 15 '18 at 09:45
-
0
something like this :
let array = ["a","b","c"]
if array.count > 0 {
for name in array {
if name.contains("a"){
print("YES")
}
}
}

Osman
- 1,496
- 18
- 22
-
You don't need the outer `if`, and you should exit the loop early, if found. – Avi May 15 '18 at 08:44
0
You check do this way,
let filtered = data.filter({$0.contains("test")})
Reference Higher order functions in swift: Filter, Map, Reduce, flatmap

PPL
- 6,357
- 1
- 11
- 30