创建一个for-in循环,在Swift中输出玩家姓名和得分

时间:2016-09-22 13:44:51

标签: arrays swift for-in-loop

var players = ["Donna", "Craig", "Brian", "Anna"]

let scores = [2, 2, 4, 5]


for (indexx, score) in scores.enumerate() {

for (index, player) in players.enumerate() {
        if indexx != index {
            continue
        }
        print("Player's Name: \(player) Score: \(score)")

    }
}

我使用迄今为止我所学到的关于for-in循环和数组的方法。是否有更充分的方法来创建一个输入玩家姓名和得分的for-in循环?

Player's Name: Donna Score: 2
Player's Name: Craig Score: 2
Player's Name: Brian Score: 4
Player's Name: Anna Score: 5

1 个答案:

答案 0 :(得分:1)

给出你的2个阵列

var players = ["Donna", "Craig", "Brian", "Anna"]
let scores = [2, 2, 4, 5]

你可以写

zip(players, scores).forEach {
    print("Player's Name: \($0.0) Score: \($0.1)")
}

这是输出

Player's Name: Donna Score: 2
Player's Name: Craig Score: 2
Player's Name: Brian Score: 4
Player's Name: Anna Score: 5