SwiftOrdered Dictionary
API
SwiftOrderedDictionary 提供了一个本地 Swift 轻量级包装器 OrderedDictionary
,它围绕内置 Swift Dictionary
类,添加了记忆其键最初添加顺序的能力。
OrderedDictionary
的 API 与 Dictionary
的 API 基本相同,所以它大多数情况下应该作为简单的直接替代品工作。不同之处在于
keys
和values
这样的变量现在是排序的,因此它们可以作为数组来实现。这意味着OrderedDictionary<K,V>.Keys == Array<K>
和OrderedDictionary<K,V>.Values == Array<V>
,因此无需像无序字典那样将它们强制转换为类型Array
。- 不适用于排序上下文中的
Dictionary
方法被删除。这特别意味着使用唯一化函数的方法和构造函数。特别是没有merge
方法。
该类型的概要 API 以伪协议的形式编写,如下所示。除非有其他说明,否则方法按正常词典执行
class OrderedDictionary<K,V> : Sequence where K : Hashable {
typealias Element = (key: K,value : V)
typealias Iterator = Array<Element>.Iterator
typealias Keys = Array<K>
typealias Values = Array<V>
init()
init(minimumCapacity: Int)
init<S>(uniqueKeysWithValues: S) where S: Sequence, S.Element == (K,V)
var count : Int { get }
var underestimatedCount: Int { get }
var isEmpty : Bool { get }
var capacity : Int { get }
func reserveCapacity(_ : Int)
subscript( _ key : K) -> V? { get, set }
subscript(_ key : K,default d: @autoclosure () -> V) -> V { get }
var first : Element? { get }
var randomElement : Element? { get }
func randomElement<T>(using _: inout T) -> Element? where T : RandomNumberGenerator
var keys : Keys { get }
var values : Values { get }
/// method not in ordinary dictionary - returns key/value pairs as an ordered list
var asArray : [Element] { get }
func updateValue(_ : V,forKey: K) -> V? )
func removeAll()
public func removeValue(forKey : K) -> V?
// method not in ordinary dictionary - can now answer the question precisely by checking the list
// of keys
public func contains(_ : K) -> Bool
}
安装
ColourWheel 可以通过 CocoaPods 获取。要安装它,只需将以下行添加到 Podfile 中。
pod 'OrderedDictionary'
作者
jdstmporter, [email protected]。