Swift中的AnyObject和Any [英] AnyObject and Any in Swift

查看:94
本文介绍了Swift中的AnyObject和Any的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道何时在Swift中使用AnyObject,何时使用Any.

I don't understand when to use AnyObject and when to use Any in Swift.

就我而言,我有字典

[字符串:???]

[String: ???]

??? :可以是整数,双精度,浮点数,字符串,数组,字典

??? : Can be Int, Double, Float, String, Array, Dictionary

有人可以向我解释Any和AnyObject之间的区别吗 以及在我的情况下该使用哪一个.

Can someone explain me the difference between Any and AnyObject and which one to use in my case.

阿拉

推荐答案

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

AnyObject is only for reference types (classes), Any is for both value and reference types.

所以你应该去[String: Any].

Any和AnyObject的类型转换

Swift提供了两种用于处理非特定类型的特殊类型:

Swift provides two special types for working with nonspecific types:

  • Any完全可以表示任何类型的实例,包括函数 类型.
  • AnyObject可以代表任何类类型的实例.
  • Any can represent an instance of any type at all, including function types.
  • AnyObject can represent an instance of any class type.

注意:

仅当您明确需要该行为并使用时,才使用AnyAnyObject. 他们提供的功能.最好总是具体一些 您希望在代码中使用的类型.

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数组. 因此,您需要将它们强制转换为所需的数组类型.

Also note that when you work with Cocoa API, it's common to receive an Array of AnyObject, this is because Objective-C arrays are NOT typified. So you need to cast them to the array type you expect.

-

编辑 :( 2015年12月22日)
在最后一条语句中,请注意,这在Swift 2.0和Xcode 7中正在改变. 苹果在Objective-C中引入了轻量级"泛型,因此许多可可API现在已经返回了正确的类型.

(december 22, 2015)
On the last statement, note that this is changing with Swift 2.0 and Xcode 7.
Apple has introduced ‘Lightweight’ generics in Objective-C so lots of Cocoa APIs now already returns the correct type.

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

(october 18, 2016)
Note that, as of Swift 3.0, Objective-C ids are now imported as Any, not anymore as AnyObject.

这篇关于Swift中的AnyObject和Any的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆