为什么 [NSDictionary allKeys] 不返回集合?
NSDictionary
是否有理由将其键返回为 NSArray
而不是 NSSet
?文档已经指出数组中键的顺序未定义,使用集合听起来合乎逻辑。
Is there a reason for NSDictionary
to return its keys as NSArray
instead of NSSet
? The documentation already states that the order of the keys in the array is undefined, it would sound logical to use a set.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 API 设计中,集合往往会被忽视。大多数情况下它们都会被包含在内,但通常会在所有其他标准数据结构之后很久才包含在内。除此之外,除了最近的 NSFastEnumeration 之外,Objective-C 中没有通用的集合或序列协议——每个集合类完全独立于所有其他集合类——并且在 API 之后切换到集合变得非常困难已经写了返回数组。
Sets tend to be somewhat neglected in API design. They'll be included most of the time, but usually long after all the other standard data structures. Add on top of that the fact that besides the very recent NSFastEnumeration, there is no general collection or sequence protocol in Objective-C — every collection class is completely independent of all the others — and it becomes very hard to switch to sets after an API has already been written that returns arrays.
我的猜测是 Apple 到处都在使用 NSArray(大多数程序员也是如此),所以这个选择是自然而然的 - 现在改变它会付出很高的成本。如果在内部使用数组,则不可变数组的副本比仅仅为了数学优雅而构建集合要便宜得多。
另请注意,
NSSet
和NSArray
没有共同的父级(当然,NSObject
除外),因此抽象此接口也是如此不可能(除了返回符合NSFastEnumeration
的内容)。当然,这只是疯狂的猜测。 ;-)
My guess is that Apple is using
NSArray
all over the place (and most programmers as well), so this choice comes naturally - and changing it now would come at a high cost. And if using arrays internally, a copy of an immutable array is much cheaper than building a set just for the sake of mathematical elegance.Also note that
NSSet
andNSArray
don't have a common parent (well, exceptNSObject
, of course), so abstracting this interface is also impossible (except for returning something that conforms toNSFastEnumeration
).Just wild speculation, of course. ;-)
我的猜测是,由于
-allKeys
返回键的副本(它不受字典支持),因此创建NSSet
需要花费很多时间与仅将键转储到平面数组相比,开销(构建树或哈希表或其他任何东西)。My guess is that, since
-allKeys
returns a copy of the keys (it's not backed by the dictionary) that creating anNSSet
is a lot of overhead (building a tree or hash table or whatever) when compared to just dumping the keys into a flat array.通常你会想对键做一些事情,在这种情况下,使用这个 NSDictionary 方法更简单:
这可以节省时间,因为现在你不需要使用谓词过滤数组,你可以在这里执行测试,你会得到一些回报。简单的。
此外,您可以通过将并发枚举选项传递给此版本的方法来利用多处理器并发性:
Usually you would want to do something with the keys, in which case it is simpler to use this NSDictionary method:
This saves time because now you don't need to filter your array using a predicate, you can just perform your test in here and you get a set back. Simple.
Furthermore, you can take advantage of multi-processor concurrency by passing the concurrent enumeration option to this version of the method:
使用 c++,std::map 提供对其键作为集合的访问。返回的集合甚至是“live”,该集合反映了当前正在进行的键集合。当然,您也可以自由复制。
use use c++, std::map provides access to its keys as a set. the set returned is even "live" , the set reflects the ongoing current set of keys. of course you are free to make a copy as well.