Twilight Pony Inc. Twilight Pony Inc. - 4 years ago 106
Swift Question

Find an object in array?

Does Swift have something like _.findWhere in Underscore.js?

I have an array of structs of type

T
and would like to check if array contains a struct object whose
name
property is equal to
Foo
.

Tried to use
find()
and
filter()
but they only work with primitive types, e.g.
String
or
Int
. Throws an error about not conforming to
Equitable
protocol or something like that.

Answer Source

FWIW, if you don't want to use custom function or extension, you can:

let array = [ .... ]
if let found = find(array.map({ $0.name }), "Foo") {
    let obj = array[found]
}

This generates name array first, then find from it.

If you have huge array, you might want to do:

if let found = find(lazy(array).map({ $0.name }), "Foo") {
    let obj = array[found]
}

or maybe:

if let found = find(lazy(array).map({ $0.name == "Foo" }), true) {
    let obj = array[found]
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download