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

Convert Array of Dictionaries into Array of Values from NSFetchRequest

我有一个使用 fetchRequest.resultType = .dictionaryResultTypeNSFetchRequest 返回的字典,返回的字典是 [Any] 并且如下所示:

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

我只想要一个值数组,像这样 [Canadiens, "Maple Leafs", Penguins"],如何将字典数组转换为仅包含值的数组?

完全获取

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)")
    }


}

替代接受的答案:

do {

    let fetchTeamNamesArray = try managedContext.fetch(fetchRequest)

    for array in fetchTeamNamesArray {

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

        teamNameArray.append(teamName)

    }

你清楚地知道结果的键和值是字符串将结果强制向下转换为[[String:String]]

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

然后将字典映射到键的值 team

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