简体   繁体   中英

Convert Array of Dictionaries into Array of Values from NSFetchRequest

I have a dictionary that is being returned from a NSFetchRequest using the fetchRequest.resultType = .dictionaryResultType the dictionary returned is [Any] and looks like the folowing:

teams [{
    team = Canadiens;
}, {
    team = "Maple Leafs";
}, {
    team = Penguins;
}]

I would like just an array of the values, like this [Canadiens, "Maple Leafs", Penguins"] , how can I convert the array of dictionaries into an array only containing the values?

Full fetch

func teamNames(managedContext: NSManagedObjectContext) {
    //print("\(self) -> \(#function)")

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Players")

    fetchRequest.fetchBatchSize = 8
    fetchRequest.propertiesToGroupBy = [#keyPath(Players.team)]
    fetchRequest.propertiesToFetch   = [#keyPath(Players.team)]
    fetchRequest.resultType          = .dictionaryResultType

    do {

        let fetchTeamNamesDictionary = try managedContext.fetch(fetchRequest)
        print("fetchTeamNamesDictionary \(fetchTeamNamesDictionary)")


    } catch let error as NSError {

        print("GoFetch|teamNames: Could not fetch. \(error), \(error.userInfo)")
    }


}

Alternate to accepted answer:

do {

    let fetchTeamNamesArray = try managedContext.fetch(fetchRequest)

    for array in fetchTeamNamesArray {

        let teamName = (array as AnyObject).value(forKey: "team") as! String

        teamNameArray.append(teamName)

    }

As you clearly know that the keys and values of the result are strings force-downcast the result to [[String:String]]

let teamArray = try managedContext.fetch(fetchRequest) as! [[String:String]]

Then map the dictionaries to its value for key team

let teamNames = teamArray.map { $0["team"]! }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM