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

时间:2017-12-04 19:18:10

标签: arrays swift dictionary nsfetchrequest

我有一个使用NSFetchRequestfetchRequest.resultType = .dictionaryResultType返回的字典,返回的字典为[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)

    }

1 个答案:

答案 0 :(得分:2)

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

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

然后将字典映射到键team

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