how I can call es request with distinct values in swift?
This is my code:
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate a
As already mentioned the key is using
fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType
and
fetchRequest.propertiesToFetch = ["propertyName"]
both are required for distinct to work
fetchRequest.returnsDistinctResults = true
The next step is to deal with the results as Swift Dictionaries and returning the wanted values.
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext = appDelegate.managedObjectContext!
//FetchRequest
let fetchRequest = NSFetchRequest(entityName: "Purchase")
fetchRequest.propertiesToFetch = ["year"]
fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType
fetchRequest.returnsDistinctResults = true
//Fetch
var error: NSError?
if let results = managedContext.executeFetchRequest(fetchRequest, error: &error) {
var stringResultsArray: [String] = []
for var i = 0; i < results.count; i++ {
if let dic = (results[i] as? [String : String]){
if let yearString = dic["year"]?{
stringResultsArray.append(yearString)
}
}
}
return stringResultsArray
}else {
println("fetch failed: \(error?.localizedDescription)")
}
return []