Search code examples
swiftvariablesbindingconditional-statementsrequire

Error - Variable binding in a condition requires an initializer


Cant solve this error, need a little help. In fact I find understand this error and why its happening. Im using dictionary to create prefixes for my list.

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

Solution

  • Seems like you are trying to group countries by the first character of their names. Dictionary has a dedicate initializer for grouping elements of an array with the given condition:

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

    example:

    let countriesList = [
        ["name": "USA"],
        ["name": "UAE"],
        ["name": "Italy"],
        ["name": "Iran"]
    ]
    
    let grouped = Dictionary(grouping: countriesList) {
        $0["name"]!.prefix(1)
    }
    
    print(grouped)
    

    prints:

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