I am revisiting Apple Curriculum books and trying to complete exercises in different ways. The problem is simple: I am given an array, which I have to loop through to count votes.
enum ClassTripDestination {
case beach, chocolateFactory
}
let tripDestinationVotes: [ClassTripDestination] = [.beach, .chocolateFactory, .beach, .beach, .chocolateFactory]
The actual array has 200 values, I shortened it here so that it wouldn't take up too much space.
Solution is quite simple:
var beach = Int()
var factory = Int()
for destination in tripDestinationVotes {
if destination == .beach {
beach += 1
} else {factory += 1}
}
But I decide to practice ternary operator and came up with this:
for destination in tripDestinationVotes {
destination == .beach ? beach += 1 : factory += 1
}
And well, as my topic states, Xcode isn't happy with this code.
Left side of mutating operator isn't mutable: result of conditional operator '? :' is never mutable
But what bothers me is that right before this exercise I completed another - quite similar. I had to search through an array of chicken.
var chickenOfInterestCount = 0
for chicken in chickens {
chicken.temper == .hilarious ? chickenOfInterestCount += 1 : nil
}
chickenOfInterestCount
And this code was executed without a single problem.
Can somebody explain to me, why is there a problem with counting the votes in the array?