NSObject 和 AnyObject 有什么区别?什么时候用这两个? [英] What is the difference between NSObject and AnyObject? When to use the two?
问题描述
我正在尝试创建一个数组来存储字符串或自定义类数组.我最好创建一本字典吗?
I'm trying to create an array to store Strings or an array of custom class. Am I better off creating a dictionary?
推荐答案
AnyObject
是 Swift 对 Objective-C 的 id
类型的表示.它比 NSObject
更通用(即每个 NSObject
都是一个 AnyObject
,但不是每个 AnyObject
都是一个 NSObject
).
AnyObject
is Swift's representation of Objective-C's id
type. It's more general than NSObject
(i.e. every NSObject
is an AnyObject
, but not every AnyObject
is a NSObject
).
在问题的另一部分 - 取决于您打算如何使用该结构.为泛型结构使用更特殊的类(Swift 的类型化数组或字典)将使您享受强类型的好处,而使用更通用的类型将使您更加动态.实际上,这取决于您打算使用该类的目的.
On the other part of the question - depends on how you intend to use the structure. Using a more particular class for the generic structure (Swift's typed array or dictionary) will allow you to enjoy the benefits of the strong typing, whereas using a more generic type will allow you to be more dynamic. Really it depends on what you intend to use the class for.
这篇关于NSObject 和 AnyObject 有什么区别?什么时候用这两个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!