gpt4 book ai didi

dictionary - 快速空字典错误? Playground vs 项目

转载 作者:行者123 更新时间:2023-11-28 09:18:21 27 4
gpt4 key购买 nike

这段代码可以在 playground 中运行

var detaildata:Dictionary=[:]
detaildata = ["apple":"hello"]
detaildata["orange"]="byebye"

此代码在项目中不起作用

class ViewController: UIViewController{
var detaildata:Dictionary=[:]

override func viewDidLoad() {
super.viewDidLoad()
detaildata = ["apple":"hello"]
detaildata["orange"]="byebye" // Error -> 'Dictionary' is not identical to 'Dictionary<key,Value>'
}
}

你知道为什么吗?

我认为是相同的代码。

最佳答案

该代码在我的 playground 中不起作用,也不应在您的 playground 中起作用。当您声明一个 Dictionary 时,您需要显式或通过类型推断为其指定键和值类型。所有这些都将起作用:

var dict1 = ["apple": "hello"]       // inferred
var dict2: [String: String] = [:] // explicit
var dict3: Dictionary<String, String> = ["apple": "hello"] // longest version

这些都不起作用:

var dict3: Dictionary = [:]          // type inference impossible
var dict4 = [:] // same

关于dictionary - 快速空字典错误? Playground vs 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26491602/

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