Can't change tuple in array
I am trying to change a tuple in an array, however when I try
emo = (type:emo.type,strength:increaseStrength(emo.strength))
it gives me an error
"cannot assign to 'let' value 'emo'
here is my code:
var emotions : [(type : String, strength: Int)] = [("happy",0),("scared",0),("tender",0),("excited",0),("sad",0)]
func increaseStrength(i:Int)->Int {
switch i {
case 0: return 1
case 1: return 2
case 2: return 3
case 3: return 0
default :return 0
}
}
@IBAction func HappyBA(sender: AnyObject) {
for emo in emotions {
if (emo.type == "happy" ){
emo = (type:emo.type,strength:increaseStrength(emo.strength))
}
}
println(emotions)
}
If there is a better way to complete the assignment, tell me I am so appreciated! Thank..
source to share
There is no point in prescribing emo
, even if you can. This is not the same as replacing the corresponding object in the array - that's what you want to do. emo
- copy; even if you were to set its property, it would not affect one back in the array. And of course setting a variable won't magically return to the array!
Here's one solution. Instead of looping emotions
through your for loop, a thru loop enumerate(emotions)
. You now have a tuple of the index number along with the emotion. If this is the correct type of emotion, write to the array by index number.
for (ix,emo) in enumerate(emotions) {
if emo.type == "happy" {
emotions[ix] = (type:emo.type,strength:increaseStrength(emo.strength))
}
}
Or you can use map
.
emotions = emotions.map {
emo in
if emo.type == "happy" {
return (type:emo.type,strength:increaseStrength(emo.strength))
} else {
return emo
}
}
source to share