String error when accessing element from a Map

When looping over weapons, I get the following error:

var weapons = {}
    weapons["Bow"] = 5
    weapons["Sword"] = 15
    weapons["Battle-Axe"] = 20

for (item in weapons.keys) {
    System.print("%(item) Damage: " + (weapons[item]))
}
Right operand must be a string.
[compile line 7] in (script)

>Solution :

When you do weapons[item], you’re accessing a number (damage) not a string. You need to use %():

for (item in weapons.keys) {
  System.print("%(item) Damage: %(weapons[item])")
}

# Output:
Sword Damage: 15
Bow Damage: 5
Battle-Axe Damage: 20

Leave a Reply