![](/img/trans.png)
[英]Convert an array of structs into array of dictionaries with values stated as strings
[英]Convert Array of Dictionaries into Array of Values from NSFetchRequest
我有一本字典,它是使用fetchRequest.resultType = .dictionaryResultType
从NSFetchRequest
返回的,返回的字典是[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"]! }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.