![](/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.