为什么词典不采用MutableCollectionType协议? [英] Why does not Dictionary adopt MutableCollectionType protocol?

查看:56
本文介绍了为什么词典不采用MutableCollectionType协议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实现自定义集合类型(并使其遵循CollectionType协议)的同时,我想知道为什么MutableCollectionType没有被Dictionary类型采用?

While implementing a custom collection type (and therefore making it to adhere to CollectionType protocol) I came to wonder why MutableCollectionType is not adopted by Dictionary type?

摘自MutableCollectionType的文档:

支持下标分配的集合.

A collection that supports subscript assignment.

对于任何符合MutableCollectionType类型的实例,:

For any instance a of a type conforming to MutableCollectionType, :

a[i] = x
let y = a[i]

等效于:

a[i] = x

让y = x

因此,字典也采用此协议似乎是逻辑上的".但是,在检出头文件和文档之后,似乎只有Array和相关类型可以做到这一点.

Therefore, it would seem "logical" that Dictionary also adopts this protocol. However, after checking out header files as well as docs, it seems that only Array and related types do that.

关于MutableCollectionType或关于Dictionary或两者都有什么特别之处?我的类似字典的自定义集合类型是否也应出于某种原因避免采用MutableCollectionType?

What's so special about MutableCollectionType, or about Dictionary, or both for that matter? Should my dictionary-like custom collection type also avoid adopting MutableCollectionType for some reason?

推荐答案

从标题开始:

遍历任意序列可能会消耗掉它,而 collection 则是多次遍历:可以仅通过保存其索引来重新访问任何元素.

Whereas an arbitrary sequence may be consumed as it is traversed, a collection is multi-pass: any element may be revisited merely by saving its index.

这对字典没有意义,因为字典是无序的.仅仅因为用"howdy"键输入的条目现在位于索引2上,并不意味着它将在一分钟后位于索引2上.特别是,说在索引2中插入此键 "是没有意义的-键和内部哈希值提供了顺序.索引没有自己的持久寿命.因此,它是一个集合(具有索引),但不是可变的集合(您不能通过索引将其写入).

That makes no sense for a dictionary, as a dictionary is unordered. Just because the entry keyed by "howdy" is at index 2 right now does not mean it will be at index 2 one minute from now. In particular, it makes no sense to say "insert this key at index 2" - it is the keys and the internal hashing that provide the order. The indexes have no persistent life of their own. Thus, it is a collection (it has indexes), but not a mutable collection (you can't write into it by index).

这篇关于为什么词典不采用MutableCollectionType协议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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