Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 Struct Searching by parameter with contains

I have array of structs and I don't know really how to use search by one of the struct's parameter.

My struct looks like:

struct Actor {
   var name: String!
   var posterURL: String!

    init(_ dictionary: [String: Any]) {
       name = dictionary["name"] as! String
       posterURL = dictionary["image"] as! String
    }
}

So, I've tried to use predicate

let actorSearchPredicate = NSPredicate(format: "name contains[c] %@", text)
filterredActors = (actors as NSArray).filtered(using: actorSearchPredicate)

But, when I'm trying to type anything, it crashes with error

[<_SwiftValue 0x10657ffb0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.'

What is the right way of using predicate search with structs? Thank you

like image 464
Vitalyz123 Avatar asked Oct 11 '25 08:10

Vitalyz123


1 Answers

NSPredicate is not needed, Swift got convenience methods to check case insensitive

whether the receiver contains a given string by performing a case insensitive, locale-aware search.

filterredActors = actors.filter { $0.name.localizedCaseInsensitiveContains(text) }

and case and diacritic insensitive

whether the receiver contains a given string by performing a case and diacritic insensitive, locale-aware search.

filterredActors = actors.filter { $0.name.localizedStandardContains(text) }
like image 175
vadian Avatar answered Oct 16 '25 12:10

vadian