Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an Array an AnyObject in Swift?

Tags:

ios

swift

I'm having trouble understanding the limitations of AnyObject.

You can see from the header that Array is a struct. Nevertheless, this code works:

var whatobject : AnyObject
whatobject = [1,2]

And it's not just literal arrays:

var whatobject : AnyObject
let arr = [1,2,3]
whatobject = arr

However, I can't assign a struct that I make to whatobject:

struct S {}
var whatobject : AnyObject
whatobject = S() // error

So an array isn't really a struct after all?

like image 651
matt Avatar asked Jun 11 '14 03:06

matt


1 Answers

that's the fun part when bridging comes in...

by default, Swift bridge

  • Int (and friends) to NSNumber
  • String to NSString
  • Dictionary to NSDictionary

so compiler will change them to object if need to

and you can do

var num : AnyObject = 1 // I think num is now NSNumber
var arr : AnyObject = [1,2,3] // I think arr is now NSArray of @[@1,@2,@3]

and you can't assign sturct/enum to AnyObject because they are not object type (you can use Any to hold them)

like image 179
Bryan Chen Avatar answered Nov 16 '22 13:11

Bryan Chen