Petravd1994
Petravd1994

Reputation: 903

How to cast (Any)? to Int

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?

Upvotes: 0

Views: 6040

Answers (2)

clearlight
clearlight

Reputation: 12615

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
}

Upvotes: -2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726489

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
    }
}

Upvotes: 6

Related Questions