gpt4 book ai didi

swift - 无法通过下标赋值 : 'dict' is a 'let' constant

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

我有一个非常简单的 Swift 问题。我创建了这个函数:

var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int]) {
for (name, age) in dict {
guard age >= 0 else {
dict[name] = 0
continue
}
}
}
correctAges(dict:dictAges)

但我不明白错误:

"cannot assign through subscript: 'dict' is a 'let' constant, dict[name] = 0"

我该如何解决?

最佳答案

函数的输入参数在函数体内是不可变的,而 Dictionary 是值类型,所以您在函数内部看到的 dict 实际上是原始 dictAges 的副本>。当您使用值类型作为其输入参数调用函数时,该输入参数按值传递,而不是按引用传递,因此在函数内部您无法访问原始变量。

要么将 dict 输入参数声明为 inout,要么如果您更喜欢更实用的方法,则从函数返回字典的变异版本。

函数式方法:

var dictAges : [String: Int] = ["John":40, "Michael":20, "Bob": -16]

func correctAges(dict:[String:Int])->[String:Int] {
var mutatedDict = dict
for (name, age) in mutatedDict {
guard age >= 0 else {
mutatedDict[name] = 0
continue
}
}
return mutatedDict
}
let newDict = correctAges(dict:dictAges) //["Michael": 20, "Bob": 0, "John": 40]

输入输出版本:

func correctAges(dict: inout [String:Int]){
for (name,age) in dict {
guard age >= 0 else {
dict[name] = 0
continue
}
}
}

correctAges(dict: &dictAges) //["Michael": 20, "Bob": 0, "John": 40]

关于swift - 无法通过下标赋值 : 'dict' is a 'let' constant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47310863/

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