Just getting your code to work, changing it as little as possible:
let scores = [2, 2, 8, 6, 1, 2, 1]
var players = ["Bob", "Alice", "James", "Gini", "John", "Alex", "Ray"]
func nameAndScores(name: [String], scores: [Int]) -> [(String, Int)] {
var result: [(String, Int)] = []
for (names, scores) in zip(players, scores) {
result.append((names, scores))
}
return result
}
let pairs = nameAndScores(name: players, scores: scores)
See ForāIn Loops and zip(_:_:)
.
An even shorter way to write it:
let scores = [2, 2, 8, 6, 1, 2, 1]
var players = ["Bob", "Alice", "James", "Gini", "John", "Alex", "Ray"]
func nameAndScores(name: [String], scores: [Int]) -> [(String, Int)] {
return Array(zip(name, scores))
}
let pairs = nameAndScores(name: players, scores: scores)
See init(_:)
.
What you probably want to do instead (unless context you havenāt told us about prevents it):
let scores = [
"Bob": 2,
"Alice": 2,
"James": 8,
"Gini": 6,
"John": 1,
"Alex": 2,
"Ray": 1
]
See Dictionary
.
As @Nevin said, if you ever need to keep track of more than just the score, you should probably use a structure that models the data better:
struct Player {
let name: String
var score: Int
let handicap: Int
}
let playerDefinitions = [
Player(name: "Bob", score: 2, handicap: 0),
Player(name: "Alice", score: 2, handicap: 0),
Player(name: "James", score: 8, handicap: -2),
Player(name: "Gini", score: 6, handicap: -1),
Player(name: "John", score: 1, handicap: 1),
Player(name: "Alex", score: 2, handicap: 0),
Player(name: "Ray", score: 1, handicap: 1)
]
var players = Dictionary(uniqueKeysWithValues: playerDefinitions.map({ ($0.name, $0) }))
players["John"]?.score += 1
See Structures & Classes.