How to get back search results based on order of the search key array

We have the following function that returns the search results for an array of key passed into the query:
func getItems(ids: [String]) -> [CBLDocument] {
var documents: [CBLDocument] = CBLDocument
let query = database.viewNamed(“byCode”).createQuery()
query.keys = ids
var error: NSError?
let result = query.run(&error)
while let row = result?.nextRow() {
documents.append(row.document)
}
return documents
}

The problem is that the results are not being returned in the order of the keys in the array. Could you please advice as to how we could achieve that and maintain the order?

Many thanks

Here is the view that’s being queried:

    let productByCodeView = database.viewNamed("byCode")
    productByCodeView.setMapBlock({ (doc, emit) in
        var code:String = "";
        if (doc["type"] as! String == "item") {
            if (doc["code"] != nil) {
                code = doc["code"] as! String
                if (count(code.utf16) > 0) {
                    emit(code, nil)
                }
            }
        }
    }, version: "0.03")

Hi Alfie,

The results of the query are sorted in the order the documents are indexed in the view.

See this video at 8m52s where Jens explains how you might want the result to be in another order: https://youtu.be/mFQTGiCEHrE?t=8m52s

James

Thanks very much for the information James.