如何使用数组来存储每轮的分数

时间:2016-12-27 15:12:16

标签: swift

我想在每一轮以编程方式创建一个新数组来存储该轮数。所以说我有

var roundNumber = 3
var team1Score = 5
var team2Score = 7

我将这些存储在数组中

var scores = [Int]()

scores.append(team1Score)
scores.append(team2Score)
print (scores)

如何动态更改名称,然后存储该轮次中的分数,以便我以后加载它们。或者将该数组存储到另一个数组中并创建一个新数组,以便稍后调用它并使用当前轮次分数填充新数组而不键入每个新数组?

3 个答案:

答案 0 :(得分:1)

我更喜欢使用结构数组,如下所示

struct Result {
    let round: Int
    let team1Score: Int
    let team2Score: Int
}

var results = [Result]()

// round 1
let result = Result(round: 1, team1Score: 7, team2Score: 5)
results.append(result)

// round N or maybe could be done in loop
let resultN = Result(round: 2, team1Score: 17, team2Score: 10)
results.append(resultN)

答案 1 :(得分:0)

class ScoreCard{
    var round:Int?
    var player1Score:Int?
    var player2Score:Int?
}
var s = [ScoreCard]()
let scoreCard = ScoreCard()
scoreCard.round = 1
scoreCard.player1Score = 10
scoreCard.player2Score = 20
s.append(scoreCard)

这将完成我的工作。

答案 2 :(得分:0)

您可以使用字典和元组来表示您的目标。 将每轮的分数存储在一个元组中:

var round1 = (team1score: 1, team2score: 3)

然后创建一个字典(dict)来存储具有与之关联的名称的元组:

var scores: [String: (team1score: Int, team2score: Int)] = [:]
scores["1"] = round1

var anotherRound = (team1score: 12, team2score: 32)
scores["some round"] = anotherRound

print (scores)

如果您需要,可以定义字典以使用轮次数作为关键字。然后代码看起来像:

var round1 = (team1score: 1, team2score: 3)
var scores: [Int: (team1score: Int, team2score: Int)] = [:]
scores[1] = round1

var anotherRound = (team1score: 12, team2score: 32)
scores[4] = anotherRound

print (scores)

对于使用分数数据的东西,您可以轻松迭代:

for (round, score) in scores {
    print("round \(round) had winner score \(max(score.team1score,score.team2score))")
}