LazyFilterBidirectionalCollection>' t

2019-09-19 06:22发布

问题:

After I convert my project from swift 2.3 to swift 3 , I got this error in Realm Filter I can't get filter result in array :

func filterUsers(_ searchText: String, completion: (([Lawyer]) -> Void)) {

        let bgRealm = try! Realm()            // Filter the whole list of users



let results = bgRealm.objects(Lawyer.self).filter { (cc) -> Bool in
    cc.name.contains2(searchText) ||
        cc.name.contains2(searchText) ||
        cc.phoneNumber2.contains2(searchText)

}
    print(results)


    completion(results)

}

回答1:

filter, map, etc. are lazy operations on the Results returned by objects. This is implemented in types such as LazyFilterBidirectionalCollection<T>. To actually perform the filtering and get an array of results, you need to promote this collection to an array by wrapping in an Array initializer (e.g. Array(bgRealm.objects...))

From the docs:

Queries return a Results instance, which contains a collection of Objects. Results have an interface very similar to Array and objects contained in a Results can be accessed using indexed subscripting. Unlike Arrays, Results only hold Objects of a single subclass type. All queries (including queries and property access) are lazy in Realm. Data is only read when the properties are accessed.