Search code examples
swiftanyobject

Type Casting For AnyObject to represent instances of any reference type


 var array = [AnyObject]()
 struct Test {}
 array.append(Test())

When I write this code in the play ground it gives me the following error Type 'Test' does not conform to protocol 'AnyObject'

I am guessing it is failing because struct is a value type not a reference type. But when I run this code

var array = [AnyObject]()
array.append(1)
array.append(2.0)
array.append("3")

It works but these are all also value types but in this case no error is given Why?


Solution

  • For your success case, there is some conversion going on behind the scenes.

    Try adding this at the end of your appends to see what's happening:

    for item in array {
        print(item.dynamicType)
    }