0

I want to filter on my custom object. My custom object look

class Requestlist: NSObject, NSCoding {
let artist: String
let title: String
let id: String
let type: String

init(artist: String, title: String, id: String, type: String) {
    self.artist = artist
    self.title = title
    self.id = id
    self.type = type
   }
}

But the program keeps crashing with this code:

    let textInput = txbSearch.text
    let pred = NSPredicate(format: "ANY artist contains[c] %@ OR title contains[c] %@",textInput!)
    let filteredArray = (Constants.liveRequestlist as NSArray).filtered(using: pred)
    print(filteredArray)

The code runs on KeyboardChange and must be updated when the keyboard input change like a live search. I also want to search on a part of an artist or title. (Like the SQL Like operator)

2
  • Already tried. But that doensn't work for Swift 3. imgur.com/a/lC9NP Commented Mar 15, 2018 at 14:27
  • What is the error that is thrown? Commented Mar 15, 2018 at 14:42

1 Answer 1

2

Two issues:

  • Any is only for key paths or to-many relationships.
  • The second parameter (representing the second %@) is missing.

    let pred = NSPredicate(format: "artist contains[c] %@ OR title contains[c] %@",textInput!, textInput!)
    

It's highly recommended to use the native Swift filter API:

let filteredArray = Constants.liveRequestlist.filter{ $0.artist.range(of: textInput!, options: [.caseInsensitive]) != nil 
                                               || $0.title.range(of: textInput!, options: [.caseInsensitive]) != nil }
Sign up to request clarification or add additional context in comments.

Comments