2

I'm struggling to understand why an instance of AnyObject is equal to an array of Anyobject, i.e. Why this statement var one: AnyObject = [AnyObject]() is valid?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Thor
  • 9,638
  • 15
  • 62
  • 137
  • 1
    It is not uncommon that arrays are also objects (or can be bridged to objects). In Java, you can do `Object one = new Object[3];` as well. – Thilo Aug 10 '16 at 00:37
  • 2
    For what it's worth, all you have to do to make this stop working is remove `import Foundation` from the top of your file. A true Swift array is not an `AnyObject`. – nhgrif Aug 10 '16 at 00:40
  • Thanks everyone for helping out! love SO community so much lol – Thor Aug 10 '16 at 00:43

1 Answers1

3

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

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • sorry, I guess what i'm trying to ask is why is it legal to assign an array of AnyObject to an instance of AnyObject? – Thor Aug 10 '16 at 00:32
  • 1
    Because of automatic bridging to NSArray. – jtbandes Aug 10 '16 at 00:35
  • 2
    @TonyStark: When you declare a variable like this `var one: AnyObject` you can put into it any thingconform to the `AnyObject` protocol. Since the Swift array is bridged to `NSArray` which conforms to `AnyObject` then the code is valid. – Luca Angeletti Aug 10 '16 at 00:35
  • @appzYourLife that make sense. Thank you so much for helping out! this has puzzled me for awhile now :) – Thor Aug 10 '16 at 00:36