本文介绍了为什么数组是Swift中的AnyObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解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) to NSNumber
  • String to NSString
  • Dictionary to NSDictionary

所以编译器将改变它们到对象如果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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 20:09