1

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?

TomKo1
  • 214
  • 2
  • 14

3 Answers3

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
  • Can I do something like this in Unit Testing (not in regular code)? :) – TomKo1 May 15 '18 at 09:35
  • 1
    There'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
  • okay never mind :) – TomKo1 May 15 '18 at 09:50
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
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