问题描述
我无法理解AnyObject的局限性。
I'm having trouble understanding the limitations of AnyObject.
您可以从标题中看到Array是一个结构体。然而,此代码的工作:
You can see from the header that Array is a struct. Nevertheless, this code works:
var whatobject : AnyObject
whatobject = [1,2]
和它不只是文字数组:
var whatobject : AnyObject
let arr = [1,2,3]
whatobject = arr
但是,我无法为 whatobject
指定一个结构:
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?
推荐答案
当桥接进入时,这是有趣的部分......
that's the fun part when bridging comes in...
默认情况下,Swift bridge
by default, Swift bridge
-
Int
(和朋友)到NSNumber
-
字符串
到NSString
-
字典
来的NSDictionary
Int
(and friends) toNSNumber
String
toNSString
Dictionary
toNSDictionary
所以编译器将改变它们到对象如果NEE d到
so compiler will change them to object if need to
你可以做到
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]
您无法分配 sturct
/ 枚举
来 AnyObject
,因为它们不是对象类型(可以使用任何
来持有它们)
and you can't assign sturct
/enum
to AnyObject
because they are not object type (you can use Any
to hold them)
这篇关于为什么数组是Swift中的AnyObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!