在编程时我是新手,刚开始学习 Swift.对于我正在努力解决的以下阵列概念,我们将不胜感激. 如何缩短以下编码,以便减少If语句的数量.因此,当选择“battlename = name [0]”索引时,语句会自动
如何缩短以下编码,以便减少If语句的数量.因此,当选择“battlename = name [0]”索引时,语句会自动选择相同索引级别的相应怪物,而不必使用如此多的If语句.
希望我有意义.
var names = ["Lancelot", "Arthur", "Gawain", "Galahad"] var monsters = ["Dragon", "Boar", "Giant", "Griffin"] let battlename = names[1] print(battlename, "Vs.", monsters) if battlename == names[0] { print(battlename, "Vs.", monsters[0]) } else if battlename == names[1] { print(battlename, "Vs.", monsters[1]) } else if battlename == names[2] { print(battlename, "Vs.", monsters[2]) } else if battlename == names[3] { print(battlename, "Vs.", monsters[3]) }您可以使用以下单个条件替换所有条件:
if let index = names.indexOf(battlename) { print(battlename, "Vs.", monsters[index]) }
此外,如果您想要在简介中打印怪物名称列表,而不是仅打印数组,您可以将项目作为字符串加入:
print(battlename, "Vs.", monsters.joinWithSeparator(", ")) // "Arthur Vs. Dragon, Boar, Giant, Griffin"