为什么数组是Swift中的AnyObject?

时间:2023-01-12 16:10:10

I'm having trouble understanding the limitations of AnyObject.

我无法理解AnyObject的局限性。

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

您可以从标题中看到Array是一个结构体。不过,这段代码有效:

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:

但是,我无法为whatobject分配一个结构:

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

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

那么数组毕竟不是一个真正的结构?

1 个解决方案

#1


8  

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

当桥接进来时,这是有趣的部分......

by default, Swift bridge

默认情况下,Swift桥

  • Int (and friends) to NSNumber
  • Int(和朋友)到NSNumber

  • String to NSString
  • 字符串到NSString

  • Dictionary to NSDictionary
  • 字典到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)

并且您不能将sturct / enum分配给AnyObject,因为它们不是对象类型(您可以使用Any来保存它们)

#1


8  

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

当桥接进来时,这是有趣的部分......

by default, Swift bridge

默认情况下,Swift桥

  • Int (and friends) to NSNumber
  • Int(和朋友)到NSNumber

  • String to NSString
  • 字符串到NSString

  • Dictionary to NSDictionary
  • 字典到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)

并且您不能将sturct / enum分配给AnyObject,因为它们不是对象类型(您可以使用Any来保存它们)