gpt4 book ai didi

swift - 在 .forEach 闭包 Swift 中使用 .sortInPlace

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

我正在尝试对字典中的数组进行排序,但出现错误。这是我试过的代码。我缺少什么以及为什么不能编译?

var dict = [Int: [String]]()

dict[1] = ["Zack", "James", "Bill", "Quin", "Mike", "Adam"]

dict[1]?.sortInPlace()


dict.forEach{$0.1.sortInPlace()} // error: cannot use mutating member on immutable value of type '[String]'

编辑:在意识到 for each 循环默认分配一个常量后,我能够使以下代码工作:

db.forEach{db[$0.0] = $0.1.sort()}

最佳答案

Swift,默认情况下将闭包内的每个值分配为不可变的。您可以通过使用 var 将变量声明为可变来修改默认行为,

dict.forEach({ (key: Int, var value: [String]) in
value.sortInPlace()
print(value)
})

关于swift - 在 .forEach 闭包 Swift 中使用 .sortInPlace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33487658/

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