oscarimonbox
2/15/2016 - 9:33 AM

Buscar un objeto en una array con un determinado atributo

Buscar un objeto en una array con un determinado atributo

203

SWIFT 3/4

Check if the element exists

if array.contains(where: {$0.name == "foo"}) {
   // it exists, do something
} else {
   //item could not be found
}
Get the element

if let foo = array.first(where: {$0.name == "foo"}) {
   // do something with foo
} else {
   // item could not be found
}
Get the element and its offset

if let foo = array.enumerated().first(where: {$0.element.name == "foo"}) {
   // do something with foo.offset and foo.element
} else {
   // item could not be found
}
Get the offset

if let fooOffset = array.index(where: {$0.name == "foo"}) {
    // do something with fooOffset
} else {
    // item could not be found
}
NSMutableArray* arrayPhones = [[NSMutableArray alloc] init];
[arrayPhones addObject:phone];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"deviceId = %@", deviceId];
NSArray *filteredArray = [arrayPhones filteredArrayUsingPredicate:predicate];




// For number kind of values:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF = %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

// For string kind of values:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];

// For any object kind of value (yes, you can search objects also):
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", value];
NSArray *results = [array_to_search filteredArrayUsingPredicate:predicate];