swift - 错误 - 条件中的变量绑定(bind)需要初始值设定项

标签 swift variables binding conditional-statements require

无法解决此错误,需要一点帮助。事实上,我发现理解这个错误及其发生的原因。我使用字典为我的列表创建前缀。

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/

相关文章:

string - 如何快速替换字符串中的特定单词?

ios - 如何在 Swift 中处理深色模式的自定义颜色

events - MVVM 绑定(bind)到 CLR 事件

binding - Aurelia + Select2 自定义元素未传播选定更改

wpf - 访问验证结果

ios - 平移手势识别器选择器不起作用

swift - 如何将 UIImage 设置为 ttf 字体中的图标

php - 将全局变量和参数传递给 PHP 中的函数

c - 根据用户输入声明数组

python - 在 Python、wx.python 中使用变量名中的占位符