gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 12:13:32 25 4
gpt4 key购买 nike

我有一个使用 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 { $0["team"]! }

关于arrays - 从 NSFetchRequest 将字典数组转换为值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47640435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com