如何拥有“自适应”结构名称?

时间:2016-12-28 06:20:20

标签: swift

所以我正在创建一个结构并将结果放入一个像这样的数组

struct roundResults {
    let round: Int
    let team1Total: Int
    let team2Total: Int
}

var allResults = [roundResults]()

然后我填充结构并将其附加到数组中,如此

func createStruct(){
    let (result) = roundResults(round:RoundNumber , team1Total:team1GameTotal , team2Total:team2GameTotal)
    allResults.append(result)
}

当我从数组中打印数据时,它给了我这个

[Game.ScoreScreen.roundResults(round: 1, team1Total: 0, team2Total: 3), 
Game.ScoreScreen.roundResults(round: 2, team1Total: 0, team2Total: 10)]

我想要实现的是,不是将结构标记为

Game.ScoreScreen.roundResults

我得到roundResults代表当前回合的内容

我创建了一个新变量,并在创建结构时尝试使用此var代替圆形结果,但这似乎不起作用

func createCall(){
    roundCall = "results" + String(RoundNumber)
}

我想要的是像let (result) = (roundCall)(round:RoundNumber...这样的东西,所以我有一个简单的方法来拉取每个数组,取决于我目前在哪一轮,打印数据看起来像

[Game.ScoreScreen.results1(round: 1,
Game.ScoreScreen.results2(round: 2, etc...

1 个答案:

答案 0 :(得分:1)

您目前只使用结构的默认打印行为。

您可以使您的结构符合[CustomStringConvertible][1] protocol by implementing the description`属性。这使您可以指定以字符串格式表示结构的方式,例如用于打印。

以下是一个例子:

struct roundResults: CustomStringConvertible {
    let round: Int
    let team1Total: Int
    let team2Total: Int

    var description: String {
        return "Round \(round) results: Team 1: \(team1Total) vs Team 2: \(team2Total)" // TODO: Adjust this to work as you wish.
    }
}

现在,当您打印阵列时,它会显示:

["Round 1 results: Team 1: 0 vs Team 2: 3", "Round 2 results: Team 1: 0 vs Team 2: 10"]