无法解决此错误,需要一点帮助。事实上,我发现理解这个错误及其发生的原因。我使用字典为我的列表创建前缀。
func cretaeExtendedTableViewData() {
// ...
for country in self.countriesList {
let countryKey = String(country.name.prefix(1)) // USA > U
if var countryValues = countriesDictionary[countryKey] {
countryValues.append(country)
countriesDictionary[countryKey] = countryValues
} else {
// ...
}
}
}
最佳答案
似乎您正在尝试按国家/地区名称的第一个字符对国家/地区进行分组。 Dictionary
有一个专用的初始值设定项,用于根据给定条件对数组元素进行分组:
let grouped = Dictionary(grouping: countriesList) {
$0["name"]!.prefix(1)
}
示例:
let countriesList = [
["name": "USA"],
["name": "UAE"],
["name": "Italy"],
["name": "Iran"]
]
let grouped = Dictionary(grouping: countriesList) {
$0["name"]!.prefix(1)
}
print(grouped)
打印:
[ "I": [
["name": "Italy"],
["name": "Iran"]
],
"U": [
["name": "USA"],
["name": "UAE"]
]
]
关于swift - 错误 - 条件中的变量绑定(bind)需要初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58414257/