I'm starting with Swift and I'm stuck with this problem for a while now. I'm trying to go through an array of cards and add them into a dictionary under a key that represents the turn they were played on.
I made a dictionary turnsWithCardsPlayed that should contain a key:value pairs like this - "Turn 2":[Card1, Card2, Card3]. The problem is if the key has no value associated with it yet, it doesn't append the card.
let turnsWithCardsPlayed = [String: [Card]]()
for card in arrayOfCards {
turnsWithCardsPlayed["Turn " + card.turn]!.append(card)
}
I solved the problem by including an if statement that checks if there is any value and if it is not, it creates a blank array and then appends the card. However the solution is clunky and too long in my opinion. Is there a better way to do it?
let turnsWithCardsPlayed = [String: [Card]]()
for card in arrayOfCards {
if var turnCardArray = turnsWithCardsPlayed["Turn " + card.turn] {
turnsWithCardsPlayed["Turn " + card.turn]!.append(card)
} else {
turnsWithCardsPlayed["Turn " + card.turn] = []
turnsWithCardsPlayed["Turn " + card.turn]!.append(card)
}
}
Thank you all :)