How to get distinct results from a single field in

2019-04-16 00:22发布

I'm trying to get a distinct list of all of the values from the "flightNumber" field in my "LogLine" table. But everything I've tried has resulted in the fetch request returning the full list of flight numbers, with duplicates.

I've followed the answers from these questions:

Swift Core Data - Request with distinct results

Swift 3 - NSFetchRequest Distinct Results

But can't seem to get it to work. Here is my code:

func fetchUniqueFlightNumbers() -> [[String: Int16]]? {
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "LogLine")
    request.resultType = NSFetchRequestResultType.dictionaryResultType
    request.returnsDistinctResults = true
    request.propertiesToFetch = ["flightNumber"]

    do {
        let results = try persistenceContainer.viewContext.fetch(request) as! [[String: Int16]]
        return results
    } catch {
        print("Couldn't read flight numbers from DB \(error)")
        return nil
    }
}

The results I'm getting are:

[["flightNumber": 1], ["flightNumber": 1], ["flightNumber": 2], ["flightNumber": 2]]

I want to get the result [1,2] but I'm getting [1,1,2,2].

The attribute "flightNumber" is an Integer 16.

Is there something wrong with my code, or has something changed in Swift 4?

EDIT:

I realized that I'm only seeing this behavior in testing, when my persistent store is configured as an NSInMemoryStoreType. So it isn't as much of a problem, I'll just have to rethink the unit tests for this part of the code. I am curious why I'm seeing this difference in behavior between the two store types though.

0条回答
登录 后发表回答