Combining Two Conditions in Nspredicate

How do you combine two conditions in NSPredicate? I am using the following statement and I would like to add another condition that compares the the password with the contents of a textfield using AND:

request.predicate = NSPredicate(format: "username = %@", txtUserName.text!)
0

3 Answers

As already said, you can use logical operators like "AND", "OR" in predicates. Details can be found in Predicate Format String Syntax in the "Predicate Programming Guide".

As an alternative, use "compound predicates":

let p1 = NSPredicate(format: "username = %@", "user")
let p2 = NSPredicate(format: "password = %@", "password")
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [p1, p2])

This is useful for more complex expressions, or if you want to build a predicate dynamically at runtime.

4

Try this

request.predicate = NSPredicate(format: "username = %@ AND password = %@", txtUserName.text!, txtPassword.text!)
0

AND is exactly what you need

request.predicate = NSPredicate(format: "username = %@ AND password = %@", txtUserName.text!, txtPassWord.text!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest