谓词
谓词
一种逻辑条件的定义,用于约束对提取或内存过滤的搜索。谓词表示逻辑条件,可用于筛选对象集合。
虽然通常直接从nsComparisonPredicate、nsCompoundPredicate和nsExpression实例创建谓词,但您通常从格式字符串创建谓词,该格式字符串由nsPredicate上的类方法解析。谓词格式字符串的示例包括:
简单比较,如grade==“7”或firstname,如“shaffiq”
不区分大小写和音调符号的查找,例如name contains[cd]“itroen”
逻辑操作,如(名字如“mark”)或(姓氏如“adderley”)。
时间范围限制,例如,日期介于昨天美元和明天美元之间。
关系条件,如group.name,如“work*”
聚合操作,如@sum.items.price<1000
有关完整的语法参考,请参阅谓词编程指南。
还可以使用evaluate(with:substitutionvariables:)方法创建包含变量的谓词,以便在运行时替换具体值之前可以预先定义谓词。
官方文档中这么定义:
A definition of logical conditions used to constrain a search either for a fetch or for in-memory filtering.
Predicates represent logical conditions, which you can use to filter collections of objects. Although it's common to create predicates directly from instances of NSComparisonPredicate, NSCompoundPredicate, and NSExpression, you often create predicates from a format string which is parsed by the class methods on NSPredicate. Examples of predicate format strings include:
Simple comparisons, such as grade == "7" or firstName like "Shaffiq"
Case and diacritic insensitive lookups, such as name contains[cd] "itroen"
Logical operations, such as (firstName like "Mark") OR (lastName like "Adderley")
Temporal range constraints, such as date between {TOMORROW}.
Relational conditions, such as group.name like "work*"
Aggregate operations, such as @sum.items.price < 1000
For a complete syntax reference, refer to the Predicate Programming Guide.
You can also create predicates that include variables using the evaluate(with:substitutionVariables:) method, so that the predicate can be predefined before substituting concrete values at runtime.
创建一个谓词
init(format: String, argumentArray: [Any]?)
Initializes a predicate by substituting the values in a given array into a format string and parsing the result.
init(format: String, arguments: CVaListPointer)
Initializes a predicate by substituting the values in an argument list into a format string and parsing the result.
init(format: String, CVarArg...)
Initializes a predicate by substituting the values in an argument list into a format string and parsing the result.
func withSubstitutionVariables([String : Any]) -> Self
Returns a copy of the predicate with the predicate's variables substituted by values specified in a given substitution variables dictionary.
init(value: Bool)
Creates and returns a predicate that always evaluates to a given Boolean value.
init(block: (Any?, [String : Any]?) -> Bool)
Initializes a predicate that evaluates using a specified block object and bindings dictionary.
init?(fromMetadataQueryString: String)
Initializes a predicate with a metadata query string.
匹配谓词
Predicate
func evaluate(with: Any?) -> Bool
Returns a Boolean value indicating whether the specified object matches the conditions specified by the predicate.
func evaluate(with: Any?, substitutionVariables: [String : Any]?) -> Bool
返回一个布尔值,该值指示指定的对象在替换给定变量字典中的值后是否与谓词指定的条件匹配。
Returns a Boolean value indicating whether the specified object matches the conditions specified by the predicate after substituting in the values in a given variables dictionary.
func allowEvaluation()
强制安全解码的谓词允许计算。
Forces a predicate that was securely decoded to allow evaluation.
使用
声明一个实体类(注意dynamic声明要使用的key)并创建一个数组Array(oc叫NSMutablearray)
class People: NSObject {
/// 重点 oc是 一门动态语言 swift是静态语言所以使用的时候需要加dynamic关键字
@objc dynamic var name: String = ""
@objc dynamic var age: Int = 0
convenience init(name: String,age: Int) {
self.init()
self.name = name
self.age = age
}
override var description: String {
return "name == \(self.name), age == \(self.age)"
}
}
var infos:[People] = [
People.init(name: "张三", age: 3),
People.init(name: "张四", age: 4),
People.init(name: "张五", age: 5),
People.init(name: "李四", age: 4),
People.init(name: "李五", age: 5),
People.init(name: "李六", age: 6),
People.init(name: "王五", age: 5),
People.init(name: "王六", age: 6),
People.init(name: "王七", age: 7),
People.init(name: "赵六", age: 6),
People.init(name: "赵七", age: 7),
People.init(name: "赵八", age: 8)
]
基本比较运算符
筛选出年龄大于6岁的人 基本比较运算符>=,=>,<=,=<,>,<,!=、<>(不等于).
谓词支持点语法所以在使用swift时一定要进行dynamic处理证明他是动态的
let predicate1 = NSPredicate.init(format: "SELF.age > %d",6)
let result1 = infos.filter { (people) -> Bool in
return predicate1.evaluate(with: people)
}
print(result1)
输出结果为: [name == 王七, age == 7, name == 赵七, age == 7, name == 赵八, age == 8]
这句话类似SQlite里面的
SELECT * FROM SELF WHERE age>6;
基本的数据逻辑操作
筛选出年龄大于6岁且姓赵的人 逻辑与(AND、&&),逻辑或(.OR、||),逻辑非(NOT、 !),基本的数据逻辑操作
let predicate2 = NSPredicate.init(format: "SELF.age > %d AND SELF.name LIKE '赵*'",6)
let result2 = infos.filter { (people) -> Bool in
return predicate2.evaluate(with: people)
}
输出结果为:[name == 赵七, age == 7, name == 赵八, age == 8]
这句话类似SQlite里面的
SELECT * FROM SELF WHERE age > 6 AND name LIKE '张%'
范围运算符
过滤字符相关:BEGINSWITH 以···开始、ENDSWITH 以···结尾、CONTAINS 包含
let predicate3 = NSPredicate.init(format: "SELF.name ENDSWITH '七'")
let result3 = infos.filter { (people) -> Bool in
return predicate3.evaluate(with: people)
}
print(result3)
输出结果为:[name == 王七, age == 7, name == 赵七, age == 7]
模糊过滤字符
筛选出姓赵的人
let predicate2 = NSPredicate.init(format: "SELF.name LIKE '赵*'",6)
let result2 = infos.filter { (people) -> Bool in
return predicate2.evaluate(with: people)
}
输出结果为:[name == 赵六, age == 6, name == 赵七, age == 7, name == 赵八, age == 8]
这句话类似SQlite里面的
SELECT * FROM SELF WHERE name LIKE '张%'
正则表达式
MATCHES
使用该字段可以匹配正则表达式
let regular = 判断手机号合法的正则表达式
let phone = "xxx"
let isPhone = NSPredicate.init(format: "SELF MATCH %@",regular).evaluate(with: phone)
注意
Swift中没有想oc的NSMutablearray中提供了这个方法 所以需要在Swift里增加一个拓展
open func filtered(using predicate: NSPredicate) -> [Any]
使用该方法可以达到一致的效果
extension Array {
func filtered(using predicate: NSPredicate) -> [Element] {
return self.filter { (element) -> Bool in
return predicate.evaluate(with: element)
}
}
}