Оптимизация заполнения словаря


#1

Можно ли как-то оптимизировать код, убрав определение ключей dictionary[“key”]?

struct Cat {
    var name: String
    var country: String
}

let first = Cat(name: "First", country: "Russia")
let second = Cat(name: "Second", country: "USA") 
let third = Cat(name: "Third", country: "England")

let cats = [first, second, third]

var dictionary: [String: [Cat]] = [:]
dictionary["England"] = [] 
dictionary["USA"] = []     
dictionary["Russia"] = []  

for element in cats {
    dictionary[element.country]?.append(element)
}

#2
struct Cat {
    let name: String, country: String
}

let cats = [
    Cat(name: "First", country: "Russia"),
    Cat(name: "Second", country: "USA"),
    Cat(name: "Third", country: "England")
]

let result: [String: [Cat]] = cats.reduce(into: ["England": [], "USA": [], "Russia": []]) { $0[$1.country]!.append($1) }

print(result)

#3

Спасибо, классное решение)
Маленький вопрос – что если “ключи” приходят из сети и их значение заранее не известно, получится ли сделать что-то подобное?


#4

Пожалуйста)

struct Cat {
    let name: String, country: String
}

let cats = [
    Cat(name: "First", country: "Russia"),
    Cat(name: "Second", country: "USA"),
    Cat(name: "Third", country: "England")
]

let keys = ["Russia", "USA", "England"]

let result = cats.reduce(into: [String: [Cat]](uniqueKeysWithValues: keys.map { ($0, []) })) { $0[$1.country]?.append($1) }

print(result)