6

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?

1 Answer 1

8

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)

Sign up to request clarification or add additional context in comments.

10 Comments

Wow, I certainly hadn't thought of it that way before!
I hope Apple will change this kind of auto bridge behaviour. It introduced lots hard to find bugs.
Really? Can you give me an example?
structs are call by value and objects are call by reference, so you may modify (or not modify even you want to) something because you expect get a reference but get value (or other way around). it won't happen normally, but will cause you trouble when writing generic code. (I already give up to fight with compiler with some generic library code I want to write)
FYI, I get errors complaining about type conversions when I enter your code into a playground.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.