Search code examples
swiftnspredicate

Swift 2.1 how to create predicate


The compiler is complaining about his piece of code and not sure how to fix:

NSProcessInfo.processInfo().environment.contains("UITESTING")

And it complains that it cannot convert value of type STring to expected argument type '@noescape((String, String)) throws -> Bool

I'm using Xcode 7.3.1 with Swift 2.2


Solution

  • NSProcessInfo.processInfo().environment returns a [String : String] dictionary.

    To use contains on a dictionary you have to pass a closure, not a String.

    Examples for Swift 2:

    // This is just to make the answer easier to read
    let env = NSProcessInfo.processInfo().environment
    

    To test if the keys contain your String:

    let result = env.contains { $0.0.containsString("UITESTING") }
    

    or to test equality, for example:

    let result = env.contains { $0.0 == "UITESTING" }
    

    To test if the values contain your String:

    let result = env.contains { $0.1.containsString("UITESTING") }
    

    or equals:

    let result = env.contains { $0.1 == "UITESTING" }
    

    $0 is each item in the dictionary, .0 is the key and .1 is the value.

    To understand better, here's the long form syntax:

    let result = env.contains { (key, value) in key.containsString("UITESTING") }
    

    And in Swift 3, in case someone needs it:

    let env = ProcessInfo.processInfo.environment
    let result = env.contains { $0.key.contains("UITESTING") }
    let result = env.contains { $0.value.contains("UITESTING") }
    let result = env.contains { (key, value) in key.contains("UITESTING") }