Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot change tuple in an array

Tags:

swift

I'm trying to change a tuple in an array , however ,when I try emo = (type:emo.type,strength:increaseStrength(emo.strength)) it gives me 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 are better way to do the assignment please tell me I am so appreciated ! Thanks..

like image 716
Yank Avatar asked Jan 10 '23 02:01

Yank


1 Answers

There is no point assigning to emo even if you could do it. This is not the same as replacing the corresponding object in the array - which is what you do want to do. emo is a copy; even if you were to set a property of it, it wouldn't affect the one back in the array. And certainly setting the variable would not magically read back into the array!

Here's one solution. Instead of cycling thru emotions in your for-loop, cycle thru enumerate(emotions). Now you have a tuple of an index number along with an emotion. If this is the right emotion type, write into the array via the index number.

for (ix,emo) in enumerate(emotions) {
    if emo.type == "happy" {
        emotions[ix] = (type:emo.type,strength:increaseStrength(emo.strength))
    }
}

Or you could use map.

emotions = emotions.map  {
    emo in
    if emo.type == "happy" {
        return (type:emo.type,strength:increaseStrength(emo.strength))
    } else {
        return emo
    }
}
like image 72
matt Avatar answered Jan 18 '23 16:01

matt