Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

An NSPredicate DSL for iOS, OSX, tvOS, & watchOS. Inspired by SnapKit and lovingly written in Swift.

License

NotificationsYou must be signed in to change notification settings

KrakenDev/PrediKit

Repository files navigation

Pretty BannerTravis Build StatusCoverallsSupported PlatformsSwift Version CompatibilityCocoapods VersionCarthage CompatibleLICENSE

PrediKit

A SwiftNSPredicate DSL for iOS & OS X inspired bySnapKit, lovingly written in Swift, and created by that weird dude atKrakenDev.

If you're familiar with the intuitive feel of theSnapKit API, then you'll feel right at home with PrediKit! 💖

Documentation

Documentation is generated byJazzy and can be foundhere for your convenience!

Why create PrediKit?

Because I wanted to! Also, becauseNSPredicate creation is hard. When working withCoreData you useNSPredicates to fetch persisted objects.CoreData is hard enough, so why have the additional complexity of using a complex string-based predicate system?

The language you need to use to create predicate formats are completely string-based which can lead to a host of issues:

  • We have a tendency to misspell words and with the current system, you can build and run without ever knowing you misspelled a property name...until it's too late.
  • For many an iOS/OSX developer (myself included), they may be very unfamiliar with theSQL-like language that comes with the creation of predicate formats. In fact, an entirecheatsheet by the awesome guys atRealm was created because of this!
  • With complex predicate creation, it's easy to get string-blindness. Go ahead...try creating a complex predicate and reading it after a couple of hours. I dare you. 😎
  • If you misspell a property key name in a predicate format string but the string is parseable by theNSPredicate system, then nothing happens. It just fails silently. At least, I think it does. I'm currently writing this on 2 hours of sleep. Don't quote me on that.

What does it fix?

Well, hopefully it fixes all of the above and more. Currently, it:

  • Gives the developer a closure based way to create NSPredicates.
  • It also, through the magic of Xcode, gives you a way to autocomplete your queries. No more referencing a cheatsheet. Just hit the dot button and enjoy the autocomplete.
  • I also carefully constructed the API to read as much like a book as possible. Matching strings even have a redundant API just to be grammatically correct when specifying if a stringmatches ordoesNot.match another value.
  • Through a little runtime-magic/reflection, PrediKit will crash at runtime if you misspell a property key or supply a property key that does not exist in a specific class' property list.
  • All predicatebuilder closures do not need capture semantics as each closure is a@noescape closure.Read here if you don't know what that means 🤓.

Installation

PrediKit can be included in your project through any of these methods:

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

CocoaPods 0.39.0+ is required to build PrediKit

To integrate PrediKit through CocoaPods, make sure theuse_frameworks! line is included in your Podfile (PrediKit is written in Swift so it needs to be brought in as a framework). Make sure these lines are somewhere in yourPodfile:

use_frameworks!#for the latest version that is compatible with Swift 4.2 use:pod'PrediKit'#for the latest version that is compatible with legacy Swift 2.3 use this instead:pod'PrediKit',:git=>'https://github.com/KrakenDev/PrediKit.git',:branch=>'swift2.3'#for the latest version that is compatible with legacy Swift 2.1 use this instead:pod'PrediKit',:git=>'https://github.com/KrakenDev/PrediKit.git',:branch=>'swift2.1'

Then, run the following command:

$ pod install

Afterwards, whenever you need PrediKit, add this line to the top of the file it's being used in:

import PrediKit

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage withHomebrew using the following command:

$ brew update$ brew install carthage

To integrate PrediKit into your Xcode project using Carthage, specify it in yourCartfile:

github "KrakenDev/PrediKit"

For legacy swift versions, I am keeping the swift2.1 && swift2.3 branches open for you. However, no more dev will be done for them (I will however, happily accept pull requests for any feature I happen to add!) If you are using these legacy versions, you should be able to use this instead in your Cartfile:

github "KrakenDev/PrediKit" "swift2.1"github "KrakenDev/PrediKit" "swift2.3"

Runcarthage update to build the framework and drag the builtPrediKit.framework into your Xcode project.

Afterwards, whenever you need PrediKit, add this line to the top of the file it's being used in:

import PrediKit

Manually

If you prefer not to use either of the aforementioned dependency managers, you can integrate PrediKit into your project manually.

First, copy and paste these commands into Terminal:

git clone https://github.com/KrakenDev/PrediKit.gitopen PrediKit/Sources/

This should open a Finder window with the important files needed for PrediKit located in the Sources folder of the repo. Drag these folders into your project (preferable in a folder named "PrediKit") and code away! Since you would be copying these files into your project directly, there is no need for theimport PrediKit line in any of the files that you need it.

The downside to this is that you can not update PrediKit easily. You would need to repeat these steps each time you wanna grab the latest and greatest! 😱

Usage

PSA: IF YOU HATE STRINGLY TYPED APIs LIKE I DO, THEN CHECK OUT THE SECTION ON SWIFT 3's #keyPath() AT THE BOTTOM OF THE README!!!

PrediKit tries to makeNSPredicate creation easy.Heavily inspired bySnapKit's API, the API for PrediKit is extremely similar for people who love it as much as I do. Check it out. This example creates a predicate used to fetch aManagedObject fromCoreData:

letpredicate=NSPredicate(ManagedLegend.self){ includeIfin    includeIf.string("title").equals("The Almighty Kraken")}

To check if a property is nil:

letpredicate=NSPredicate(ManagedLegend.self){ includeIfin    includeIf.string("title").equalsNil()}

PrediKit can also query member properties. Say you have a class structure like this:

classCaptain:NSObject{varname:String}classShip:NSObject{varcaptain:Captain}

And you want to create these predicates:

letsomeCaptain=Captain()NSPredicate(format:"captain == %@ && captain.name == 'Chief Supreme'", someCaptain)

Creating the above with PrediKit is easy and expressive:

letsomeCaptain=Captain()letpredicate=NSPredicate(Ship.self){ includeIfletincludeIfShipCaptain= includeIf.member("captain", ofType:Captain.self)    includeIfShipCaptain.equals(someCaptain) &&    includeIfShipCaptain.string("name").equals("Chief Supreme")}

PrediKit also overloads the&&,||, and! operators. This allows you compound and specify whether ornot to include yourincluders (Crappy name, I know. Feel free to give me suggestions).

letpredicate=NSPredicate(ManagedLegend.self){ includeIfin    //Include any ManagedLegend instance if the property named "string" is NOT nil and does NOT equal "The Almighty Kraken"    !includeIf.string("title").equalsNil() &&    !includeIf.string("title").equals("The Almighty Kraken") &&    //Also include any ManagedLegend instance if the date property named "birthdate" is in the past or if the bool property "isAwesome" is true.    includeIf.date("birthdate").isEarlierThan(NSDate()) ||    includeIf.bool("isAwesome").isTrue()}

You can even createincluders conditionally!

letpredicate=NSPredicate(ManagedLegend.self){ includeIfinletisKrakenQuery= includeIf.string("title").equals("The Almighty Kraken")letbirthdateQuery= includeIf.date("birthdate").isEarlierThan(NSDate())letisAwesomeQuery= includeIf.bool("isAwesome").isTrueif shouldCheckBirthdate{(isKrakenQuery && birthdateQuery) || isAwesomeQuery}else{        isKrakenQuery || isAwesomeQuery}}

I don't know about y'all, but theSQL-likeIN operator was hard to wrap my head around. PrediKit makes this a little more human-readable:

letawesomePeeps=["Kraken","Cthulhu","Voldemort","Ember","Umber","Voldemort"]letpredicate=NSPredicate(ManagedLegend.self){ includeIfin    includeIf.string("title").matchesAnyValueIn(awesomePeeps)}

PrediKit also has built-in support for subquery predicates:

letpredicate=NSPredicate(ManagedLegend.self){ includeIfin    includeIf.string("title").equals("The Almighty Kraken") &&    //Only include Krakens that have more than three hungry cerberus friends    includeIf.collection("cerberusFriends").subquery(ManagedCerberus.self){        $0.bool("isHungry").isTrue()return.IncludeIfMatched(.Amount(.IsGreaterThan(3)))}}

#keyPath() + PrediKit = 💖

PrediKit becomes MUCH more expressive and safer when using Swift 3's #keyPath syntax. I don't know about you but I HATE stringly typed APIs. The best part of #keyPath is that you get autocompletion of your properties and a way to get sub properties without using PrediKit's.member functions:

letpredicate=NSPredicate(ManagedLegend.self){ includeIfin    includeIf.string(#keyPath(ManagedLegend.title)).equals("The Almighty Kraken")}letpredicate=NSPredicate(ManagedLegend.self){ includeIfin    includeIf.string(#keyPath(ManagedLegend.bestFriend.title)).equals("The Cool Elf")}

Selector Extension Pattern Variation

Personally, I love using a variation of theSelector Extension Pattern when using PrediKit. It allows you to avoid misspelling your property names when using the API. It also allows you to rename your keypath properties at will. By renaming, every instance of that keyPath used by PrediKit should give you a compiler error so you don't miss a beat and can feel safe knowing you haven't missed any property names in a name change refactor. By creating a String extension like so:

import FoundationextensionString{staticlettitle= #keyPath(Kraken.title)staticletbirthdate= #keyPath(Kraken.birthdate)staticletage= #keyPath(Kraken.age)staticletfriends= #keyPath(Kraken.friends)staticletisAwesome= #keyPath(Kraken.isAwesome)staticletisHungry= #keyPath(Kraken.isHungry)}

PrediKit becomes a lot more expressive now:

//BEFOREletpredicate=NSPredicate(ManagedLegend.self){ includeIfin    includeIf.string(#keyPath(ManagedLegend.title)).equals("The Almighty Kraken")}//AFTERletpredicate=NSPredicate(ManagedLegend.self){ includeIfin    includeIf.string(.title).equals("The Almighty Kraken")}

LICENSE

PrediKit is licensed under theMIT license. Check out theLICENSE file to learn more.

About

An NSPredicate DSL for iOS, OSX, tvOS, & watchOS. Inspired by SnapKit and lovingly written in Swift.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp