Doubt, add value of an array [Anyobject] using Swift?

Asked

Viewed 240 times

1

How would I do it in Swift?

var jogador02 = ["Teste", 0]

jogador02[1] += 1

result be equal to

jogador02 = ["teste", 1]

1 answer

2


As you mixed the types of your array, everything becomes AnyObject, soon to effect the binary sum operation you need type the data.

var jogador02 = ["Teste", 0]
var temp = jogador02[1] as! Int
temp += 1 // Pode substituir por temp++
jogador02[1] = temp

I would recommend that you create a player class with the desired attributes, in case it would look like this:

class Jogador {

  var nome = ""
  var pontuacao = 0    

}

And when it’s time to use:

var jogador = Jogador()
jogador.pontuacao += 1
  • 1

    True @Leodabus, I did not remember the name at the time and I thought I carried the same class, corrected.

  • +1 exactly this, if it were just numbers would not have the need to force the conversion to Int :)

  • 1

    Another detail you’re forcing the element’s unwrap without being sure it’s an Int, which would lead to an App crash otherwise

  • The easiest way would be to use ?? Nil coalescing Operator together with as? Int ?? 0

  • Thank you guys, everyone helped me a lot! all the answers helped a lot!

  • Another thing you must declare let jogador = Jogador() which does not prevent you from changing the punctuation and name properties.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.