I
I
Igor2021-06-27 14:38:16
Swift
Igor, 2021-06-27 14:38:16

Why can't Any be cast to Int?

Hello!
I don't quite understand why I can't cast Any directly to Int?

let str: Any = "12"
print( str as! Int )

60d8621932f5d793316955.png

At the same time, I can safely cast Any to the string
let str: Any = "12"
print( str as! String )

60d8626305d70356521337.png

It turns out that I need to cast Any first to a string, and then to Int.
let str: Any = "12"
print( Int(str as! String) ?? 0)


What is the logic behind this behaviour?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DevMan, 2021-06-27
@Lexemz

because these types do not have the same protocols:

error: protocol type 'Any' cannot conform to 'BinaryInteger' because only concrete types can conform to protocols
print( Int(str) )

and yes, cast to string and then to int.

D
dollar, 2021-06-27
@dollar

And if without quotes?

let str: Any = 12
print( str as! Int )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question