0

I am trying to cast a (Any)? value to a Integer. I am retrieving information from Firebase and I want to add the number by something else. That is why the (Any)? value needs to be a Integer. I have this:

let snapshotValues = snapshot.value as? NSDictionary
let gamesWon = snapshotValues!.value(forKey: "GamesWon")
let gamesLost = snapshotValues!.value(forKey: "GamesLost")
let totalgamesPlayedByUser = gamesWon + gamesLost

This is giving me an error that two Any? objects can not be added together. I already tried the Int(gamesWon), gamesWon as! Int, but that did not work. How to cast this as a Integer?

Petravd1994
  • 893
  • 1
  • 8
  • 24

2 Answers2

5

If you know that both keys contain Ints, you should be able to write

let gamesWon = snapshotValues!.value(forKey: "GamesWon") as! Int
let gamesLost = snapshotValues!.value(forKey: "GamesLost") as! Int

making gamesWon + gamesLost a valid Int expression.

If you are not sure if the keys are there or not, use if let statements instead:

if let gamesWon = snapshotValues!.value(forKey: "GamesWon") as? Int {
    if let gamesLost = snapshotValues!.value(forKey: "GamesLost") as? Int {
        let totalgamesPlayedByUser = gamesWon + gamesLost
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
-1

Alternatively:

var gamesWon  : Any = 1
var gamesLost : Any = 2
var totalGamesPlayedByUser : Int

if gamesWon is Int && gamesLost is Int {
   totalGamesPlayedByUser = gamesWon as! Int + gamesLost as! Int
}
clearlight
  • 12,255
  • 11
  • 57
  • 75