swift - Swift 中的 AnyObject 和 Any

标签 swift value-type reference-type

我不明白何时在 Swift 中使用 AnyObject 以及何时使用 Any

就我而言,我有一个字典

[String: ???]

??? :可以是IntDoubleFloatStringArray >字典

有人可以解释一下 AnyAnyObject 之间的区别吗? 以及在我的情况下使用哪一个。

最佳答案

AnyObject 仅适用于引用类型(类),Any 适用于值类型和引用类型。

所以你应该选择[String: Any]

Type Casting for Any and AnyObject

Swift provides two special types for working with nonspecific types:

  • Any can represent an instance of any type at all, including function types.
  • AnyObject can represent an instance of any class type.

NOTE:

Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code.

来自Swift 编程语言: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html#//apple_ref/doc/uid/TP40014097-CH22-ID342

-

另请注意,当您使用 Cocoa API 时,通常会收到 AnyObject 数组,这是因为 Objective-C 数组没有典型化。 因此您需要将它们转换为您期望的数组类型。

-

编辑:(2015 年 12 月 22 日)
在最后一个声明中,请注意,这在 Swift 2.0 和 Xcode 7 中发生了变化。
苹果推出‘Lightweight’ generics在 Objective-C 中,所以很多 Cocoa API 现在已经返回正确的类型。

编辑:(2016 年 10 月 18 日)
请注意,从 Swift 3.0 开始,Objective-C id 现在作为 Any 导入,不再作为 AnyObject 导入。

关于swift - Swift 中的 AnyObject 和 Any,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55974666/

相关文章:

ios - 如何使用持续时间为单个 UICollectionView 单元格设置动画

swift - 如何将附近的位置设置到从 Firebase 检索的 TableView 中

c# - 检查对象是否为值类型的最有效方法

c# - 不带 ref 关键字的引用传递

c# - Nullable<> 作为 ViewPage 的 TModel

ios - pushViewController 无法快速在 xib 中工作

ios - RealmSwift 数据过滤

Swift 嵌套的可选值类型(结构)和修改属性

c# - 将结构与 WCF 服务一起使用

java - 引用类型和对象类型