Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

ios - Why is an Array an AnyObject in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...