Thursday, April 14, 2022

Swift Arrays to Dictionaries with indices

The extension below is to facilitate the creation of dictionaries from arrays. In this case, the dictionary has the array element as the key and the index of that element as the value. 

Since I was only working with arrays that held unique values I added a guard statement to enforce that. If you remove it, then your the last duplicated element would have the index as its value.

extension Array where Element: Hashable {

    func toDictionary() -> [Element: Int] {

        guard Set(self).count == self.count else {

            fatalError("\(#function) requires arrays with unique values!")

        }

        return self

            .enumerated()

            .reduce(into: [Element: Int]()) { dict, tup in

                dict[tup.1] = tup.0

            }

    }


["hello", "world"].toDictionary() // ["world": 1, "hello": 0]