Swift中的AnyObject和Any

我不明白什么时候使用AnyObject和什么时候用Swift中的Any。

我的情况,我有一个字典

[String: ???]

??? :可以是Int,Double,Float,String,Array,Dictionary

有人可以解释一下Any和AnyObject之间的区别
和女巫使用在我的情况。

Alak

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而改变。
苹果在Objective-C中引入了‘Lightweight’ generics,所以很多Cocoa API现在已经返回了正确的类型。

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...