AnyStruct and AnyResource
AnyStruct is the top type of all non-resource types, i.e., all non-resource types are a subtype of it.
AnyResource is the top type of all resource types.
// Declare a variable that has the type `AnyStruct`.
// Any non-resource typed value can be assigned to it, for example an integer,
// but not resource-typed values.
//
var someStruct: AnyStruct = 1
// Assign a value with a different non-resource type, `Bool`.
someStruct = true
// Declare a structure named `TestStruct`, create an instance of it,
// and assign it to the `AnyStruct`-typed variable
//
struct TestStruct {}
let testStruct = TestStruct()
someStruct = testStruct
// Declare a resource named `TestResource`
resource Test {}
// Declare a variable that has the type `AnyResource`.
// Any resource-typed value can be assigned to it,
// but not non-resource typed values.
//
var someResource: @AnyResource <- create Test()
// Invalid: Resource-typed values can not be assigned
// to `AnyStruct`-typed variables
//
someStruct <- create Test()
// Invalid: Non-resource typed values can not be assigned
// to `AnyResource`-typed variables
//
someResource = 1However, using AnyStruct and AnyResource does not opt-out of type checking. It is invalid to access fields and call functions on these types, as they have no fields and functions.
AnyStruct and AnyResource may be used like other types, for example, they may be the element type of arrays or be the element type of an optional type.
AnyStruct is also the super-type of all non-resource optional types, and AnyResource is the super-type of all resource optional types.
Conditional downcasting allows coercing a value which has the type AnyStruct or AnyResource back to its original type.
Last updated
Was this helpful?