错误-条件中的变量绑定需要初始化

时间:2019-10-16 13:15:06

标签: 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 {
            // ...
        }
    }
}

1 个答案:

答案 0 :(得分:0)

似乎您正在尝试按国家/地区名称的首字符分组。 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"]
  ]
]