Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // CaseInsensitiveDictionary.swift
- // Created by Daniel Duan on 12/19/14.
- // Usaege Example:
- // var test = CaseInsensitiveDictionary<String, Int>()
- // test["Winter is coming"] = 1
- //
- // test["WINTER is Coming"] = test["Winter Is Coming"] // true
- // test["Hear Our Roar?"] = 1
- //
- // test.count == 2 // true
- //
- // for (word, value) in test {
- // print(word)
- // }
- import Foundation
- struct CaseInsensitiveDictionary<Key: Hashable, Value>: CollectionType, DictionaryLiteralConvertible {
- private var _data:[Key: Value] = [:]
- private var _keyMap: [String: Key] = [:]
- typealias Element = (Key, Value)
- typealias Index = DictionaryIndex<Key, Value>
- var startIndex: Index
- var endIndex: Index
- var count: Int {
- assert(_data.count == _keyMap.count, "internal keys out of sync")
- return _data.count
- }
- var isEmpty: Bool {
- return _data.isEmpty
- }
- init() {
- startIndex = _data.startIndex
- endIndex = _data.endIndex
- }
- init(dictionaryLiteral elements: (Key, Value)...) {
- for (key, value) in elements {
- _keyMap["\(key)".lowercaseString] = key
- _data[key] = value
- }
- startIndex = _data.startIndex
- endIndex = _data.endIndex
- }
- subscript (position: Index) -> Element {
- return _data[position]
- }
- subscript (key: Key) -> Value? {
- get {
- if let realKey = _keyMap["\(key)".lowercaseString] {
- return _data[realKey]
- }
- return nil
- }
- set(newValue) {
- let lowerKey = "\(key)".lowercaseString
- if _keyMap[lowerKey] == nil {
- _keyMap[lowerKey] = key
- }
- _data[_keyMap[lowerKey]!] = newValue
- }
- }
- func generate() -> DictionaryGenerator<Key, Value> {
- return _data.generate()
- }
- var keys: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Key>> {
- return _data.keys
- }
- var values: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Value>> {
- return _data.values
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement