gpt4 book ai didi

swift - (应该很简单)添加到 Swift 字典

转载 作者:搜寻专家 更新时间:2023-11-01 07:26:54 26 4
gpt4 key购买 nike

所以出于某种原因,我不能这样做...多年来一直在编写代码,自从 Swift 发布以来,不知何故,这从来都不是问题。我错过了什么吗?

var categories: [Int : Category] = [:]

现在我不能做类似 categories.setObject() 的事情,甚至做 categories[0] = Category() 仍然不会在字典,但是也不会抛出任何错误。

您甚至可以使用简单的 var dict 来完成此示例:[String : String] = [:]

注意:我意识到这可能是一个非常简单的问题,但我已经进行了挖掘……我不只是在这里发帖是因为我懒得做研究。哈哈

编辑

类别定义

struct Category {
var id: Int!
var name: String!
}

super 简单...

最佳答案

确实很简单

让我们看看

and even doing categories[0] = Category() still doesn't create that element in the dictionary, however doesn't throw any errors either.

在我的 playground 中,这段代码运行良好,并且正确创建了 Category 值。

struct Category {
init() {
print("init Category")
}
}

var categories: [Int : Category] = [:]
categories[0] = Category()

enter image description here

关于swift - (应该很简单)添加到 Swift 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35479962/

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