微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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。

原文地址:https://www.jb51.cc/swift/321293.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐