Skip to content

Instantly share code, notes, and snippets.

@ahcode0919
Last active April 17, 2017 22:54
Show Gist options
  • Save ahcode0919/ceeb2b69c171fa7b287b0cf7bd1a99e0 to your computer and use it in GitHub Desktop.
Save ahcode0919/ceeb2b69c171fa7b287b0cf7bd1a99e0 to your computer and use it in GitHub Desktop.
Custom Maps in Swift
//Custom Map functions
//Experimenting with making custom map functions
//Original Map implementation: https://github.com/apple/swift/blob/master/stdlib/public/core/Sequence.swift
extension Sequence {
func mapToDictionary<T>(_ transform: (Iterator.Element) throws -> (String, T)) rethrows -> [String: T] {
let initialCapacity = underestimatedCount
var result = [String: T]()
var iterator = self.makeIterator()
for _ in 0..<initialCapacity {
if let element = iterator.next() {
let kv = try transform(element)
result[kv.0] = kv.1
}
}
while let element = iterator.next() {
let kv = try transform(element)
result[kv.0] = kv.1
}
return result
}
}
let array = [1, 2, 3, 4, 5]
let dictionary = array.mapToDictionary { (value) -> (String, Int) in
return ("\(value)", value)
}
print(dictionary) //["1": 1, "2": 2, "3":3, "4": 4, "5": 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment