Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. // CaseInsensitiveDictionary.swift
  2. // Created by Daniel Duan on 12/19/14.
  3. // Usaege Example:
  4. // var test = CaseInsensitiveDictionary<String, Int>()
  5. // test["Winter is coming"] = 1
  6. //
  7. // test["WINTER is Coming"] = test["Winter Is Coming"] // true
  8. // test["Hear Our Roar?"] = 1
  9. //
  10. // test.count == 2 // true
  11. //
  12. // for (word, value) in test {
  13. // print(word)
  14. // }
  15.  
  16.  
  17. import Foundation
  18. struct CaseInsensitiveDictionary<Key: Hashable, Value>: CollectionType, DictionaryLiteralConvertible {
  19. private var _data:[Key: Value] = [:]
  20. private var _keyMap: [String: Key] = [:]
  21.  
  22. typealias Element = (Key, Value)
  23. typealias Index = DictionaryIndex<Key, Value>
  24. var startIndex: Index
  25. var endIndex: Index
  26.  
  27. var count: Int {
  28. assert(_data.count == _keyMap.count, "internal keys out of sync")
  29. return _data.count
  30. }
  31.  
  32. var isEmpty: Bool {
  33. return _data.isEmpty
  34. }
  35.  
  36. init() {
  37. startIndex = _data.startIndex
  38. endIndex = _data.endIndex
  39. }
  40.  
  41. init(dictionaryLiteral elements: (Key, Value)...) {
  42. for (key, value) in elements {
  43. _keyMap["\(key)".lowercaseString] = key
  44. _data[key] = value
  45. }
  46. startIndex = _data.startIndex
  47. endIndex = _data.endIndex
  48. }
  49.  
  50. subscript (position: Index) -> Element {
  51. return _data[position]
  52. }
  53.  
  54. subscript (key: Key) -> Value? {
  55. get {
  56. if let realKey = _keyMap["\(key)".lowercaseString] {
  57. return _data[realKey]
  58. }
  59. return nil
  60. }
  61. set(newValue) {
  62. let lowerKey = "\(key)".lowercaseString
  63. if _keyMap[lowerKey] == nil {
  64. _keyMap[lowerKey] = key
  65. }
  66. _data[_keyMap[lowerKey]!] = newValue
  67. }
  68. }
  69.  
  70. func generate() -> DictionaryGenerator<Key, Value> {
  71. return _data.generate()
  72. }
  73.  
  74. var keys: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Key>> {
  75. return _data.keys
  76. }
  77. var values: LazyBidirectionalCollection<MapCollectionView<[Key : Value], Value>> {
  78. return _data.values
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement