Tony Stark Tony Stark - 1 year ago 73
Swift Question

Why `var one: AnyObject = [AnyObject]()` is valid?

I'm struggling to understand why an instance of

is equal to an array of
, i.e. Why this statement
var one: AnyObject = [AnyObject]()
is valid?

Answer Source

With this code

var one: AnyObject = [AnyObject]()

You are NOT comparing 2 values.

You are just assigning an array of [AnyObject] to a variable of type AnyObject.

Since the Swift array is bridged to NSArray (which is an object) then the compiler if ok with this code.

Similar examples

In the code below we declare a variable of type AnyObject and we put an int into it. Since Int si bridged to NSNumber (which is an object) again it compiler perfectly fine

var one: AnyObject = 1

More examples

var word: AnyObject = "hello"
var condition: AnyObject = true

Blocking the bridge to NSArray

If you remove the import Foundation line from Playground then the bridge to NSArray is interrupted.

Now the swift Array which is a struct is no longer considered a valid AnyObject (structs are not Objects) and you get a compile error.

enter image description here