J. Doe
J. Doe

Reputation: 13103

Subscript error trying to get values from a class

I am trying to add up all values from a class together. This is my code:

 var allPlayersArray: [allPlayersIngame] = []

class allPlayersIngame {
        let username: String
        let uid: String
        var score: Int

        init(username: String, uid: String, score: Int) {
            self.username = username
            self.uid = uid
            self.score = score
        }
    }

var totalScore = 0
    for playerScore in self.allPlayersArray{
    if let score = self.allPlayersArray[playerScore].score{
    }//error
     totalScore += allPlayersArray[playerScore].score
    }//error
    self.averageScore = totalScore / self.allPlayersArray.count
}

The error is as followed:

Cannot subscript a value of type '[vc.allPlayersIngame]' with an index of type 'vc.allPlayersIngame'

My approach was to loop through every array element and get their score. Well this did not work out well.

Upvotes: 0

Views: 39

Answers (2)

vadian
vadian

Reputation: 285280

You are mixing up index based and item based for loop

It's either (index based)

for index in 0..<self.allPlayersArray.count {
     totalScore += allPlayersArray[index].score
}
self.averageScore = totalScore / self.allPlayersArray.count

or (item based)

for playerScore in self.allPlayersArray {
     totalScore += playerScore.score
}
self.averageScore = totalScore / self.allPlayersArray.count

or (no loop based)

let totalScore = self.allPlayersArray.map({ $0.score }).reduce(0, { $0 + $1 })

Upvotes: 1

rmaddy
rmaddy

Reputation: 318944

You are iterating the array. playerScore is already each object from the array. You can't then use that object to index the array.

And you can't unwrap a non-optional.

Change your code to:

var totalScore = 0
for playerScore in allPlayersArray {
    totalScore += playerScore.score
}
averageScore = totalScore / allPlayersArray.count

Upvotes: 1

Related Questions