ahcode0919
3/25/2017 - 5:31 PM

Custom Maps in Swift

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]