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

Error - Variable binding in a condition requires an initializer

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

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) {
    [=10=]["name"]!.prefix(1)
}

示例:

let countriesList = [
    ["name": "USA"],
    ["name": "UAE"],
    ["name": "Italy"],
    ["name": "Iran"]
]

let grouped = Dictionary(grouping: countriesList) {
    [=11=]["name"]!.prefix(1)
}

print(grouped)

打印:

[  "I": [
         ["name": "Italy"],
         ["name": "Iran"]
  ], 
   "U": [
         ["name": "USA"],
         ["name": "UAE"]
  ]
]