[swift-users] Optionals inside Dictionary where Value = Any

Dmitri Gribenko gribozavr at gmail.com
Wed Jan 6 05:20:16 CST 2016


On Wed, Jan 6, 2016 at 12:47 PM, Daniel Eggert via swift-users
<swift-users at swift.org> wrote:
> I’m storing an Int? inside a [String:Any] but I can’t retrieve it again. Is this expected behaviour or a bug in Swift?
>
> /Daniel
>
> % swift
> Welcome to Apple Swift version 2.2-dev (LLVM 3ebdbb2c7e, Clang f66c5bb67b, Swift 1f2908b4f7). Type :help for assistance.  3> let d: [String:Any] = ["foo": (nil as Int?)]
> d: [String : Any] = 1 key/value pair {
>   [0] = {
>     key = "foo"
>     value = {
>       payload_data_0 = 0x0000000000000000
>       payload_data_1 = 0x636c6f6f542f7201
>       payload_data_2 = 0x77732f736e696168
>       instance_type = 0x00000001004f6028
>     }
>   }
> }
>   4> let v = d["foo"]
> v: Any? = Some {
>   payload_data_0 = 0x0000000000000000
>   payload_data_1 = 0x0000000000000001
>   payload_data_2 = 0x0000000000000000
>   instance_type = 0x00000001004f6028
> }

I think this is a bug, but not in the code that you are showing.  'v'
is correctly typed as 'Any?'.  The issue is that the compiler does not
allow it to be downcast to 'Int?':

> v! as Int?
<REPL Input>:1:2: error: cannot convert value of type 'Any' (aka
'protocol<>') to type 'Int?' in coercion
v! as Int?

Would you mind filing a bug?

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/


More information about the swift-users mailing list