Downcasting from AnyResource?

Trying to figure out a way to allow for generic attachments to NFTs. Does anyone know if we can downcast from &ref as auth &AnyResource ? Something like
let myType: @MyType <- createMyType()
let attachments: @{Type: AnyResource} <- {Type<@MyType>(): myType}

let ref = (&attachments[tag] as auth &AnyResource?)!
let castedRef = ref as &MyType
let myType: @MyType <- createMyType()
let attachments: @{Type: AnyResource} <- {Type<@MyType>(): myType}

let ref = (&attachments[tag] as auth &AnyResource?)!
let castedRef = ref as &MyType
2 Replies
turbolent
turbolent2y ago
Yes, that is possible, as the reference is an authorized reference, which makes it downcastable. You just need to use a conditional cast (as?) or force-cast (as!), instead of a type assertion (as). as is a static check – statically, &AnyResource is not a subtype of &MyType . What you want to do is ref and try to cast it at run-time. Here's an example Playground: https://play.flow.com/83473238-9b05-4132-8464-ef210e300e0d?type=script&id=26f962de-3256-434f-8300-b28e6eccb190&storage=none
Try out this Playground project
Learn Cadence, a revolutionary new smart contract programming language written for the Flow blockchain.
Giovanni S
Giovanni S2y ago
Very helpful, thanks for the example!