Ayon Saha Ayon Saha - 1 year ago 117
Swift Question

NSPredicate array for NSCompoundPredicate

Please Help me, i want to make a coredata get function in Swift 2.2 NSPredicate array for NSCompoundPredicate

public func loadData(entityName: String, filters: [String: String] = [:], dataFault: Bool = true) -> [NSManagedObject] {
var listItems: [NSManagedObject]?
let delegate = UIApplication.sharedApplication().delegate as? AppDelegate

if let context = delegate?.managedObjectContext {
let fetchRequist = NSFetchRequest(entityName: entityName)
if (filters.count > 0) {
var predicte: [NSPredicate]
for (key, value) in filters {
let p1:NSPredicate = NSPredicate(format: "%K == %@", key, value as NSObject)
fetchRequist.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicte)
fetchRequist.returnsObjectsAsFaults = dataFault
let results = try context.executeFetchRequest(fetchRequist)
listItems = results as? [NSManagedObject]
catch let err {

print("context Error")
return listItems!


There show error on predicte.appendContentsOf(p1)

Answer Source

In your code, p1 is not a CollectionType, so you need to use append, not appendContentsOf:


Also, you need to initialize your predicte appropriately:

            var predicte: [NSPredicate] = []
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download