How to cast Any to Int in Swift

I want to save the value from the "points" key from a dictionary called myInfo in

myPoints
variable so I can use it in another function. I have been trying to cast it as Int, but the value when printed out is always
0
. Meanwhile, if I just print out
temp
, it prints the value out correctly.

result with

print(type(of: temp)) is
Optional< Any >

Replies

Could you show how you call the function dictionaryBoolean ?

What is the value of the parameter.

How did you define the value for "points" key ?


Probably, myInfo["points"] returns nil; you should check with:

print(myInfo["points"])


That may be because myInfo has no "points" key defined.


In any case,- Why do you force unwrap

public func dictionaryBoolean(_ myInfo: [AnyHashable : Any]!) -> Bool {


just declare

public func dictionaryBoolean(_ myInfo: [AnyHashable : Any]) -> Bool {

if I just print out

temp
, it prints the value out correctly.

Please show the result of print out temp.

What is the actual type of the value that you're putting into the dictionary? If you set the value of key "points" to (for example) an UInt8 value,

retrieving it as an Int will fail exactly as you've shown.


That's because Swift doesn't do implicit numeric conversions for you.

When you edit your initial post, please explain what you changed.


It is really confusing to have answered to a post and then have the question changed.