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

Related tags

Text PrediKit
Overview

Pretty Banner Travis Build Status Coveralls Supported Platforms Swift Version Compatibility Cocoapods Version Carthage Compatible LICENSE

PrediKit

A Swift NSPredicate DSL for iOS & OS X inspired by SnapKit, lovingly written in Swift, and created by that weird dude at KrakenDev.

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

Documentation

Documentation is generated by Jazzy and can be found here for your convenience!

Why create PrediKit?

Because I wanted to! Also, because NSPredicate creation is hard. When working with CoreData you use NSPredicates 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 the SQL-like language that comes with the creation of predicate formats. In fact, an entire cheatsheet by the awesome guys at Realm 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 the NSPredicate 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 string matches or doesNot.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 predicate builder 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 the use_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 your Podfile:

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 with Homebrew using the following command:

$ brew update
$ brew install carthage

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

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"

Run carthage update to build the framework and drag the built PrediKit.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.git
open 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 the import 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 make NSPredicate creation easy. Heavily inspired by SnapKit'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 a ManagedObject from CoreData:

let predicate = NSPredicate(ManagedLegend.self) { includeIf in
    includeIf.string("title").equals("The Almighty Kraken")
}

To check if a property is nil:

let predicate = NSPredicate(ManagedLegend.self) { includeIf in
    includeIf.string("title").equalsNil()
}

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

class Captain: NSObject {
    var name: String
}
class Ship: NSObject {
    var captain: Captain
}

And you want to create these predicates:

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

Creating the above with PrediKit is easy and expressive:

let someCaptain = Captain()
let predicate = NSPredicate(Ship.self) { includeIf
    let includeIfShipCaptain = 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 or not to include your includers (Crappy name, I know. Feel free to give me suggestions).

let predicate = NSPredicate(ManagedLegend.self) { includeIf in
    //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 create includers conditionally!

let predicate = NSPredicate(ManagedLegend.self) { includeIf in
    let isKrakenQuery = includeIf.string("title").equals("The Almighty Kraken")
    let birthdateQuery = includeIf.date("birthdate").isEarlierThan(NSDate())
    let isAwesomeQuery = includeIf.bool("isAwesome").isTrue

    if shouldCheckBirthdate {
        (isKrakenQuery && birthdateQuery) || isAwesomeQuery
    } else {
        isKrakenQuery || isAwesomeQuery
    }
}

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

let awesomePeeps = ["Kraken", "Cthulhu", "Voldemort", "Ember", "Umber", "Voldemort"]
let predicate = NSPredicate(ManagedLegend.self) { includeIf in
    includeIf.string("title").matchesAnyValueIn(awesomePeeps)
}

PrediKit also has built-in support for subquery predicates:

let predicate = NSPredicate(ManagedLegend.self) { includeIf in
    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:

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

Selector Extension Pattern Variation

Personally, I love using a variation of the Selector 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 Foundation

extension String {
    static let title = #keyPath(Kraken.title)
    static let birthdate = #keyPath(Kraken.birthdate)
    static let age = #keyPath(Kraken.age)
    static let friends = #keyPath(Kraken.friends)
    static let isAwesome = #keyPath(Kraken.isAwesome)
    static let isHungry = #keyPath(Kraken.isHungry)
}

PrediKit becomes a lot more expressive now:

//BEFORE
let predicate = NSPredicate(ManagedLegend.self) { includeIf in
    includeIf.string(#keyPath(ManagedLegend.title)).equals("The Almighty Kraken")
}
//AFTER
let predicate = NSPredicate(ManagedLegend.self) { includeIf in
    includeIf.string(.title).equals("The Almighty Kraken")
}

LICENSE

PrediKit is licensed under the MIT license. Check out the LICENSE file to learn more.

Comments
  • Builder needs method for querying object properties

    Builder needs method for querying object properties

    Case where we want to query an object with related objects, such as:

    class Captain: NSObject {
        var name: String
    }
    class Ship: NSObject {
        var captain: Captain
    }
    NSPredicate(format: "captain == %@", someCaptain)
    NSPredicate(format: "captain.name == 'Chief Supreme'")
    

    There currently is no method to match an object property (example 1), or to match a related object's property (example 2).

    Are there currently any plans for this?

    opened by djbe 14
  • Parameters are bound to the wrong field

    Parameters are bound to the wrong field

    Let's say I have the following code:

    let predicate = NSPredicate(Shipment.self) { includeIf in
        let includeIfState = includeIf.member(Selector(ShipmentRelationships.currentState.rawValue), ofType: State.self).string(Selector(StateAttributes.stateRaw.rawValue))
    
        let noOffer = includeIf.member(Selector(ShipmentRelationships.acceptedOffer.rawValue), ofType: Offer.self).equalsNil
        let cancelled = includeIfState.equals(State.State.Cancelled.rawValue)
        let expired = includeIf.number(Selector(ShipmentAttributes.pickupTimeTo.rawValue)).isLessThanOrEqualTo(soon)
        let sender = includeIf.member(Selector(ShipmentRelationships.sender.rawValue), ofType: Sender.self).equals(data)
    
        sender && noOffer && !cancelled && !expired
    }
    

    Unexpectedly, the resulting predicate is something like this:

    sender == 1464553718.353965 AND acceptedOffer == nil AND (NOT currentState.stateRaw == "cancelled") AND (NOT pickupTimeTo <= <Sender: 0x7fe2cb708720> (entity: Sender; id: 0xd000000000080000 x-coredata://F5039107-C745-4046-B0B5-5F71ED5738B7/Sender/p2 ; data: {...}))

    As you can see, the parameters of the sender and expired sub-predicates have been exchanged.

    Side note: I'm using variables inside the block because this is a simplified example. In the actual code, the final predicate is composed of different sub-predicates depending on some filter parameter.

    opened by djbe 10
  • Minimal iOS version that PreditKit supports

    Minimal iOS version that PreditKit supports

    I used PrediKit in two projects installed through CocoaPods.

    In my new one I used Carthage and now XCode throws an error: Module file's minimum deployment target is ios8.3 v8.3: .../Carthage/Build/iOS/PrediKit.framework/Modules/PrediKit.swiftmodule/i386.swiftmodule

    What I'm doing wrong or did in my previous two projects?

    opened by av0c0der 6
  • Correct the spelling of CocoaPods in README

    Correct the spelling of CocoaPods in README

    This pull request corrects the spelling of CocoaPods 🤓 https://github.com/CocoaPods/shared_resources/tree/master/media

    Created with cocoapods-readme.

    opened by ReadmeCritic 6
  • Swift 4.2 Compilation errors trying to build in Debug

    Swift 4.2 Compilation errors trying to build in Debug

    In the latest swift migration there are two lies of code in #IF DEBUG blocks that weren't migrated along with the rest. This causes compilation errors when trying to build in debug.

    I have the fix done locally for normal development, but it would be nice to fix for first pod installs and the like.

    The problems are in MemberQuery.swift on line 48 and PredicateBuilder.swift on line 150. Both require changing String(type) to String(describing: type)

    opened by NerdBird 4
  • Xcode 10, Swift 4.2 update

    Xcode 10, Swift 4.2 update

    Update the project to use Xcode 10 and Swift 4.2

    Updating pod version to 4.2 (not very sure how versioning is maintained for this project, probably synced with Swift version)

    There was some compilation issue also with the project due to the new build system, for that, I have to remove copy phase (watchOS and tvOS Info.plist copy) to iOS and OSX target.

    Also Bool argument converting to CVarArgs crash as they give nil, so using NSNumber(value: bool) for boolean parameter in NSPredicate initializer.

    Let me know in case any other modification is required for this PR to be merged. Thanks

    opened by aksswami 2
  • Consider creating a new release now that Swift 4 support has been added

    Consider creating a new release now that Swift 4 support has been added

    Just a house keeping issue...since a new release wasn't created when Swift 4 support was added back in May, integrating with CocoaPods requires referencing the master branch or the Swift 4 commit.

    opened by gcox 1
  • Installed in CocoaPods and having compile issues

    Installed in CocoaPods and having compile issues

    Hello, I installed it, and while running it in Swift 4.2, I keep getting the following error. I get it on both MemberQuery.swift and PredicateBuilder.swift

    /Pods/PrediKit/Sources/Queries/MemberQuery.swift:48:26: Cannot invoke initializer for type 'String' with an argument list of type '(T.Type)'

    Please Help!

    opened by chadbrochill317 1
  • Remove default implementation Reflectable for NSObject

    Remove default implementation Reflectable for NSObject

    Hi, I use your nice PrediKit to filter realm Results, works pretty good, but needs particular implementation of the properties() method My variant:

    extension Object: Reflectable {
        public static func properties() -> [Selector] {
            guard let schema = self.sharedSchema() else { return [] }
            let properties = schema.properties.map {
                Selector($0.name)
            }
    
            let computedProperties = schema.computedProperties.map {
                Selector($0.name)
            }
    
            return properties+computedProperties
        }
    }
    

    Problem is the following: Object inherited from NSObject, so I can't override your implementation in the NSObject extension

    opened by kolbasek 3
Releases(5.1.1)
  • 5.1.1(Feb 24, 2019)

  • 4.0.0(Sep 19, 2016)

    Not too much of an overhaul. However, in order to support Swift 3.0, there were a couple of changes that needed to be made.

    • First off, the use of PrediKit in Swift 3 caused a bunch of unused result warnings. This has been fixed by assigning the @discardableResult attribute to any function that returned a FinalizableIncluder<T>. This change shouldn't affect anything you are already doing.
    • One breaking change is to variables that returned a FinalizableIncluder<T> instance. These needed to be converted to functions since you can't mark variables with attributes. The unused result warnings wouldn't go away until I converted these variables to functions so I can mark them with @discardableResult attribute.

    If your code uses these variables (for example, the use of includeIf.string(property).isEmpty), then you need to add an open and close paren to the end of the variable.

    This means that current use of these variables will be returning a () -> FinalizableIncluder<T> function pointer instead of the result of the function. This may result in errors that look like this: "Binary operator '&&' cannot be applied to operands of type 'FinalizedIncluder' and '() -> FinalizedIncluder'". The fix is to simply tack on a () to the end of the closure operand value.

    • Another breaking change is the change of all includers to use Strings instead of Selectors. With the advent of Swift 3, I want to encourage you to use Swift 3's #keyPath() syntax to help you ensure the correctness of your property paths at compile time. Since #keyPath() returns a string value, it just made sense to switch over to using Strings now. However, this now gives you a chance to use PrediKit unsafely. Remember, with great power comes great responsibility. So I'll say it again:

    DON'T STRINGIFY YOUR PROPERTIES, USE #KEYPATH FOR HAPPINESS INSTEAD!

    Source code(tar.gz)
    Source code(zip)
  • 3.0.2(Jul 11, 2016)

  • 3.0.1(May 31, 2016)

  • 3.0(May 30, 2016)

    Breaking changes have been made as well. Most classes have been renamed for clarity and PrediKit.swift has been split up into manageable chunks in their own files for any potential contributors.

    We've also added support for passing in instances of NSArray to the matchesAnyValueIn query.

    Source code(tar.gz)
    Source code(zip)
  • 2.0.6(May 30, 2016)

  • 2.0.5(May 30, 2016)

    Arguments weren't being parsed or handled correctly for arbitrary includer combination arrangements. This caused arguments to be switched around. We now respect the order of the combinations specified by the developer as the Great Gatsby intended it.

    Source code(tar.gz)
    Source code(zip)
  • 2.0.4(May 29, 2016)

  • 2.0.3(May 28, 2016)

  • 2.0.2(May 19, 2016)

    Before, we were creating many predicates to take advantage of the proper predicate format when combining includers. Now we use only strings and create a proper predicate at the very end of the builder closure.

    Source code(tar.gz)
    Source code(zip)
  • 1.0.2(May 18, 2016)

Owner
Hector Matos
Hector Matos
🌍⏩📄 Convert ISO8859 1-16 Encoded Text to String in Swift. Supports iOS, tvOS, watchOS and macOS.

ISO8859 Convert ISO8859 1-16 Encoded Text to String in Swift. Usage let encoding = ISO8859.part1 let string = String([...], iso8859Encoding: encoding)

Devran Cosmo Uenal 18 Jan 2, 2023
iOS & OSX Syntax Highlighter.

Highlightr Highlightr is an iOS & macOS syntax highlighter built with Swift. It uses highlight.js as it core, supports 185 languages and comes with 89

J.P. Illanes 1.4k Dec 23, 2022
A Swift framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber.

PhoneNumberKit Swift 5.3 framework for parsing, formatting and validating international phone numbers. Inspired by Google's libphonenumber. Features F

Roy Marmelstein 4.7k Jan 8, 2023
A Cross-Platform String and Regular Expression Library written in Swift.

Guitar ?? A Cross-Platform String and Regular Expression Library written in Swift. About This library seeks to add common string manipulation function

Arthur Ariel Sabintsev 659 Dec 27, 2022
Fully open source text editor for iOS written in Swift.

Edhita Fully open source text editor for iOS written in Swift. http://edhita.bornneet.com/ What Edhita means? Edhita (Romaji) == エディタ (Katakana) == Ed

Tatsuya Tobioka 1.2k Jan 1, 2023
Marky Mark is a parser written in Swift that converts markdown into native views.

Marky Mark is a parser written in Swift that converts markdown into native views. The way it looks it highly customizable and the supported markdown syntax is easy to extend.

M2mobi 287 Nov 29, 2022
Lightweight library to set an Image as text background. Written in swift.

![](https://img.shields.io/badge/Swift 2-compatible-4BC51D.svg?style=flat-square) Simple and light weight UIView that animate text with an image. Demo

Lucas Ortis 552 Sep 9, 2022
Example Thesaurus app written in Swift

Words Simple Thesaurus built with Moby data. Building You'll need CocoaPods to build the app. To install CocoaPods, run the following command in Termi

Sam Soffes 47 Jun 29, 2022
Markdown parsing and rendering for iOS and OS X

CocoaMarkdown Markdown parsing and rendering for iOS and macOS CocoaMarkdown is a cross-platform framework for parsing and rendering Markdown, built o

Indragie Karunaratne 1.2k Dec 12, 2022
Swift String Validator. Simple lib for ios to validate string and UITextFields text for some criterias

Swift String validator About Library for easy and fastest string validation based on сciterias. Instalation KKStringValidator is available through Coc

Kostya 17 Dec 21, 2019
CodeMirror-Swift is a lightweight wrapper of CodeMirror for macOS and iOS

CodeMirror-Swift is a lightweight wrapper of CodeMirror for macOS and iOS. Features ?? Lightweight CodeMirror wrapper (build 5.52.2) ✅ 100% Native Swi

Proxyman 86 Dec 30, 2022
A library for formatting strings on iOS and macOS

Sprinter Introduction What? Why? How? Usage Installation Integration Localization Thread Safety Advanced Usage Introduction What? Sprinter is a librar

Nick Lockwood 168 Feb 6, 2022
Powerful text framework for iOS to display and edit rich text.

YYText Powerful text framework for iOS to display and edit rich text. (It's a component of YYKit) Features UILabel and UITextView API compatible High

null 8.8k Jan 4, 2023
String (and more) validation for iOS

Swift Validators ?? String validation for iOS. Contents Installation Walkthrough Usage Available validators License ReactiveSwift + SwiftValidators Wa

George Kaimakas 241 Nov 13, 2022
A simple and customizable Markdown Parser for Swift

MarkdownKit MarkdownKit is a customizable and extensible Markdown parser for iOS and macOS. It supports many of the standard Markdown elements through

Bruno Oliveira 687 Dec 18, 2022
OysterKit is a framework that provides a native Swift scanning, lexical analysis, and parsing capabilities. In addition it provides a language that can be used to rapidly define the rules used by OysterKit called STLR

OysterKit A Swift Framework for Tokenizing, Parsing, and Interpreting Languages OysterKit enables native Swift scanning, lexical analysis, and parsing

Swift Studies 178 Sep 16, 2022
Easiest way to create an attributed UITextView (with support for multiple links and from html)

AttributedTextView Easiest way to create an attributed UITextView (with support for multiple links and html). See the demo app and the playground for

Edwin Vermeer 430 Nov 24, 2022
MarkdownView is a WKWebView based UI element, and internally use bootstrap, highlight.js, markdown-it.

MarkdownView is a WKWebView based UI element, and internally use bootstrap, highlight.js, markdown-it.

Keita Oouchi 1.8k Dec 21, 2022
An easy way to add mentions to uitextview like Facebook and Instagram

OEMentions An easy way to add mentions to uitextview like Facebook and Instagram. It also include a tableview to show the users list to choose from. T

Omar Alessa 48 Oct 23, 2022