简体   繁体   English

从NSFetchRequest将字典数组转换为值数组

[英]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: 我有一本字典,它是使用fetchRequest.resultType = .dictionaryResultTypeNSFetchRequest返回的,返回的字典是[Any] ,看起来像以下内容:

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? 我只想要一个值数组,例如[Canadiens, "Maple Leafs", Penguins"] ,如何将字典数组转换为仅包含值的数组?

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]] 如您所知,结果的键和值是字符串,将结果强制向下转换为[[String:String]]

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

Then map the dictionaries to its value for key team 然后将字典映射到关键team价值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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