Swift `results.allResults()` removes data

Hello. Relatively new to the CBL and the forums. We have a very simple Swift issue when trying to print the results of a query.

In this example, the person collection has three documents, so the expected output to console is three “test” strings.

let collection = try! db.collection(name: "person")
let query = QueryBuilder.select(SelectResult.all()).from(DataSource.collection(collection!))

let results = try! query.execute()

//print(results.allResults().count) //causes the following code to not work

for row in results { //will not run if print statement is called
    print(“test”)
}

Note that the //print line is commented. If that line is uncommented, there is no output.

It seems that this results.allResults() is mutating results to where they are all removed.

We investigated the API and there’s no mention of that call .allResults() blowing out the data. It appears it should just return an Array os Result objects. Is removing the results expected behavior?

https://docs.couchbase.com/mobile/3.2.0/couchbase-lite-swift/Classes/ResultSet.html#/s:18CouchbaseLiteSwift9ResultSetC10allResultsSayAA0D0CGyF

As the docs you pasted say, ResultSet conforms to the Swift Sequence protocol. The Swift docs for Sequence point out:

The Sequence protocol makes no requirement on conforming types regarding whether they will be destructively consumed by iteration. As a consequence, don’t assume that multiple for -in loops on a sequence will either resume iteration or restart from the beginning

ResultSet does destructively consume the rows during iteration.

3 Likes

Apart from what @jens said, it’s an error in the doc’s codesnippet that needs to be fixed. After calling allResults(), the iterator is all enumerated. Sorry for confusion.

3 Likes

Great info - thanks for the speedy response.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.