如何施放(任何)?至国际

Pet*_*994 0 downcast swift

我正在尝试投射(任何)?值为整数。我正在从 Firebase 检索信息,并且想通过其他内容添加该号码。这就是为什么(任何)?值需要是一个整数。我有这个:

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

这给了我一个错误,两个 Any? 对象不能添加在一起。我已经尝试过 Int(gamesWon), gamesWon as!Int,但这不起作用。如何将其转换为整数?

das*_*ght 6

如果你知道两个键都包含Ints,你应该能够写

let gamesWon = snapshotValues!.value(forKey: "GamesWon") as! Int
let gamesLost = snapshotValues!.value(forKey: "GamesLost") as! Int
Run Code Online (Sandbox Code Playgroud)

做出gamesWon + gamesLost有效的Int表达。

如果您不确定密钥是否存在,请改用if let语句:

if let gamesWon = snapshotValues!.value(forKey: "GamesWon") as? Int {
    if let gamesLost = snapshotValues!.value(forKey: "GamesLost") as? Int {
        let totalgamesPlayedByUser = gamesWon + gamesLost
    }
}
Run Code Online (Sandbox Code Playgroud)