I recently answered a question that had me wondering if I could simplify this below code without creating an extra function:
for object in objects {
if let type = object["type"] where !type.isEmpty, let name = object["name"] {
print(pokemonTypeDefenseChart[type])
for weakness in pokemonTypeDefenseChart[type]! {
if pokemonWeaknessChart[weakness] == nil {
pokemonWeaknessChart[weakness] = []
}
pokemonWeaknessChart[weakness]?.append(name)
}
}
if let typeTwo = object["typeTwo"] where !typeTwo.isEmpty, let name = object["name"] {
for weakness in pokemonTypeDefenseChart[typeTwo]! {
if pokemonWeaknessChart[weakness] == nil {
pokemonWeaknessChart[weakness] = []
}
pokemonWeaknessChart[weakness]?.append(name)
}
}
}
Essentially the code loops through objects (list of pokemon) and is designed to add all of the pokemon weak to type (and optionally typeTwo).
I ended up just refactoring the for
statements inside the if let
statements into a function, but I was wondering if it was possible to compress these without an extra function. The only difference is the type.
I know I could simplify it a bit by using a map instead of for
loops but I wanted to keep it more understandable for the question.
Any ideas?