Skip to content

Instantly share code, notes, and snippets.

@therealbnut
Created April 15, 2016 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save therealbnut/c223d90a34bb14448b65fc6cc0ec70ac to your computer and use it in GitHub Desktop.
Save therealbnut/c223d90a34bb14448b65fc6cc0ec70ac to your computer and use it in GitHub Desktop.
Dictionary interface adjustment
// Playground compatible, not meant to be an ideal implementation, mainly for the usage examples.
public struct NewDictionary<Key: Hashable, Value>
: MutableCollectionType, CollectionType, DictionaryLiteralConvertible
{
public typealias KeyCollection = LazyMapCollection<[Key:Value],Key>
public typealias ValueCollection = LazyMapCollection<[Key:Value],Value>
public typealias Index = DictionaryIndex<Key,Value>
public typealias Generator = ValueCollection.Generator
private var storage: [Key:Value]
private init(storage: [Key:Value]) {
self.storage = storage
}
public init(dictionaryLiteral elements: (Key, Value)...) {
var storage = [Key:Value](minimumCapacity: elements.count)
for (key,value) in elements {
storage[key] = value
}
self.storage = storage
}
public subscript (position: Key) -> Value? {
get { return storage[position] }
set { storage[position] = newValue }
}
// necessary for conformance?
public subscript (position: Index) -> Value {
get { return storage[keys[position]]! }
set { storage[keys[position]] = newValue }
}
private var keys: KeyCollection { return storage.keys }
public var startIndex: Index { return storage.keys.startIndex }
public var endIndex: Index { return storage.keys.endIndex }
func map<T>(@noescape transform: (Generator.Element) throws -> T) rethrows -> NewDictionary<Key,T> {
var storage = [Key:T](minimumCapacity: self.storage.count)
for (key,value) in self.storage {
storage[key] = try transform(value)
}
return NewDictionary<Key,T>(storage: storage)
}
public func enumerate() -> GeneratorSequence<DictionaryGenerator<Key,Value>> {
return GeneratorSequence(storage.generate())
}
public func generate() -> Generator {
return storage.values.generate()
}
}
var newDictionary: NewDictionary = ["a": 1, "b": 2]
for value in newDictionary {
print(value)
}
for key in newDictionary.keys {
print("key: ", key)
}
for (key, value) in newDictionary.enumerate() {
print("key: ", key, "value: ", value)
}
let mappedDictionary: NewDictionary = newDictionary.map { $0 * 2 + 1 }
print(mappedDictionary)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment