Is there a tutorial for using predicates in Swift?

Hi,

In P.106 of this book, there’s a link to Apple’s Predicate Programming Guide.

[Predicate Programming Guide](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ Predicates/AdditionalChapters/Introduction.html)

But it is in Objective-C. While I plan on learning Objective-C in the near future, I wonder if anyone have come across a good tutorial on using predicates in Swift?

Thanks,

Is there anything specific that isn’t working? It isn’t really convenient having ObjC when you are getting used to reading Swift but the syntax of the predicate construction itself is basically exactly the same.

But there is a good predicate article at NSHipster, and it is Swift 2.

I also found the NSHipster article as well. But I still didn’t understand how array operations and block operations work. They were mentioned in the NSHipster article but I felt a little more lost after reading those sections.

How are you with blocks in general?

The block form of NSPredicate is really powerful, because instead of having to know how to express your criteria in the predicate syntax you are writing a little function to pick things out. Do you understand the example given in the NSHipster article?

let shortNamePredicate = NSPredicate { (evaluatedObject, _) in
    return (evaluatedObject as! Person).firstName.utf16.count <= 5
}

(people as NSArray).filteredArrayUsingPredicate(shortNamePredicate)

the evaluated object is the thing that the predicate is going to test against. In this case that’s an element of the array named people on which filteredArrayUsingPredicate is being used. The return value of this little program is a boolean, if it returns true then the filtered array will contain the item and if it returns false then it will not. The test that provides that boolean result is that the length of the name is less than 5.

If you wanted to you could use that one short example for pretty much everything you need to do with predicates - just remember to return true for a thing you want and false for a thing you don’t.

I understand the concept of blocks, but I don’t try to seek out using them in everything I do probably because I’m not comfortable with them.

I had to read through the example carefully to understand what it is trying to do. I will definitely have to play around with NSPredicates more just to get a better understanding of them. Even though the book doesn’t cover it in detail, it is basically required to interact with Core Data so I’m looking forward to going through all the apps in the book.