reduce函数正在打印一个空字典[:]



我在这个问题中成功地将字典键作为伪代码减少了,没有真正的 json 模型。我在上一个问题中完成的目标是仅返回具有匹配值的键。所以输出是一个字典,看起来像这样 ["WoW": ["@jade", "@kalel"] .正是我需要的。当然,可能还有其他比赛,我也想归还这些比赛。

现在我有一个合适的 json 模型,reduce函数正在打印出一个空字典[:]。是.reduce(into: [String:[String]]()中的类型导致了问题吗?

所有数据都在打印,因此 json 和模型结构必须正确。

杰森

[
{
    "id": "tokenID-tqkif48",
    "name": "@jade",
    "game": "WoW",
    "age": "18"
},
{
    "id": "tokenID-fvkif21",
    "name": "@kalel",
    "game": "WoW",
    "age": "20"
}
]

用户模型

public typealias Users = [UserModel]
public struct UserModel: Codable {
public let name: String
public let game: String
// etc...
enum CodingKeys: String, CodingKey {
    case name
    case game
    // etc...

操场

guard let url = Bundle.main.url(forResource: "Users", withExtension: "json") else {
    fatalError()
}
guard let data = try? Data(contentsOf: url) else {
    fatalError()
}
let decoder = JSONDecoder()
do {
    let response = try decoder.decode([UserModel].self, from: data)
    for userModel in response {
        let userDict: [String:String] = [ userModel.name:userModel.game ]
        let reduction = Dictionary(grouping: userDict.keys) { userDict[$0] ?? "" }.reduce(into: [String:[String]](), { (result, element) in
            if element.value.count > 1 {
                result[element.key] = element.value
            }
        })
        // error catch etc
}

你的代码太复杂了。您可以简单地按game对阵列进行分组

let response = try decoder.decode([UserModel].self, from: data)
let reduction = Dictionary(grouping: response, by: {$0.game}).mapValues{ usermodel in usermodel.map{ $0.name}}

更新 我可能弄错了你想要得到的东西。下面还有另一个代码,请检查结果并选择您想要的代码。

如果你想使用reduce(into:updateAccumulatingResult:),你可以写这样的东西。

do {
    let response = try decoder.decode([UserModel].self, from: data)
    let userArray: [(name: String, game: String)] = response.map {($0.name, $0.game)}
    let reduction = userArray.reduce(into: [String:[String]]()) {result, element in
        if !element.game.isEmpty {
            result[element.name, default: []].append(element.game)
        }
    }
    print(reduction)
} catch {
    print(error)
}

如果您更喜欢 Dictionary 的初始值设定项,这可能有效:

do {
    let response = try decoder.decode([UserModel].self, from: data)
    let userArray: [(name: String, games: [String])] = response.map {
        ($0.name, $0.game.isEmpty ? [] : [$0.game])
    }
    let reduction = Dictionary(userArray) {old, new in old + new}
    print(reduction)
} catch {
    print(error)
}

两个输出:

["@jade": ["WoW"], "@kalel": ["WoW"]]

无论如何,除了userDict.keys之外,您组合循环、Dictionary(grouping:)reduce(into:)的方式使事情变得过于复杂。


添加 当您想获得带有键作为游戏的字典时:

do {
    let response = try decoder.decode([UserModel].self, from: data)
    let userArray: [(game: String, name: String)] = response.compactMap {
        $0.game.isEmpty ? nil : ($0.game, $0.name)
    }
    let reduction = userArray.reduce(into: [String:[String]]()) {result, element in
        result[element.game, default: []].append(element.name)
    }
    print(reduction)
} catch {
    print(error)
}

或:

do {
    let response = try decoder.decode([UserModel].self, from: data)
    let userArray: [(game: String, names: [String])] = response.compactMap {
        $0.game.isEmpty ? nil : ($0.game, [$0.name])
    }
    let reduction = Dictionary(userArray) {old, new in old + new}
    print(reduction)
} catch {
    print(error)
}

输出:

["WoW": ["@jade", "@kalel"]]

相关内容

  • 没有找到相关文章

最新更新