gpt4 book ai didi

Swift 字典表示

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

我正在创建一个 Swift Dictionary一些自定义对象。

下面是我定义字典的地方; var carDictionary:[String:Any] = Dictionary<String, Any>()

下面的 for 循环是我尝试从自定义对象中填充字典的地方:

 for dataPoint in dataPoints! {
carDictionary[dataPoint.value(forKey: dataPoint.dataKey)]
}

dataPoint是以下类的实例:

public class NACarDataPoint: NSObject {

var dataKey: String!
var dataValue: Any!

public override init() {
// generic initializer, generally designed to be overridden
super.init()
}

init(key: String, value: Any) {
self.dataKey = key
self.dataValue = value
}
}

我遇到了公认的常见错误

`Cannot subscript a value of type `[String : Any]` with an index of type `Any`?`

但是,我认为我对 Swift 中字典创建工作方式的理解存在一些缺失,这使我无法弄清楚这个问题 - 有人有什么建议吗?谢谢!

有类似问题的帖子: String not convertible to [AnyObject]

Cannot subscript a value of type '[String : String]?' with an index of type 'String'

Cannot subscript a value of [AnyObject]? with an index of type Int

最佳答案

您将值放在需要键下标的位置。

与数组类似,您可以像这样访问字典中的对象:

let myValue = myDictionary["myKey"]

这将检索字典中具有键“myKey”的对象。要在字典中设置值,请像这样分配给键下标:

myDictionary["myKey"] = myValue

就您而言,您的 dataPoint 类似乎具有可在字典中使用的键和值对象:

 for dataPoint in dataPoints! {
carDictionary[dataKey] = dataPoint.value(forKey: dataPoint.dataKey)
}

关于Swift 字典表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43821807/

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