Convert Swift Array to Dictionary with indexes [duplicate]

try like this:

reduce(enumerate(a), [String:UIView]()) { (var dict, enumeration) in
    dict["\(enumeration.index)"] = enumeration.element
    return dict
}

Xcode 8 • Swift 2.3

extension Array where Element: AnyObject {
    var indexedDictionary: [String:Element] {
        var result: [String:Element] = [:]
        for (index, element) in enumerate() {
            result[String(index)] = element
        }
        return result
    }
}

Xcode 8 • Swift 3.0

extension Array  {
    var indexedDictionary: [String: Element] {
        var result: [String: Element] = [:]
        enumerated().forEach({ result[String($0.offset)] = $0.element })
        return result
    }
}

Xcode 9 – 10 • Swift 4.0 – 4.2

Using Swift 4 reduce(into:) method:

extension Collection  {
    var indexedDictionary: [String: Element] {
        return enumerated().reduce(into: [:]) { $0[String($1.offset)] = $1.element }
    }
}

Using Swift 4 Dictionary(uniqueKeysWithValues:) initializer and passing a new array from the enumerated collection:

extension Collection {
    var indexedDictionary: [String: Element] {
        return Dictionary(uniqueKeysWithValues: enumerated().map{(String($0),$1)})
    }
}

Leave a Comment