这段代码让我觉得有点冗长。有没有更好的方法从命名元组数组中提取所有名称参数?
这是一个玩具示例。我们从allPlayers
类型的Swift数组中提取了allScores
和[(player : String, score : Int)]
。
var info : [(player : String, score : Int)] = Array()
let value1 = (player: "A", score: 1)
let value2 = (player: "B", score: 2)
let value3 = (player: "C", score: 3)
info.append(value1)
info.append(value2)
info.append(value3)
var allPlayers : [String] = Array()
var allScores : [Int] = Array()
for (player, score) in info {
allPlayers.append(player)
allScores.append(score)
}
答案 0 :(得分:3)
您可以使用地图功能执行此操作:
var names = info.map {
$0.player
}
// names = ["A", "B", "C"]