So I found on here this method to doing so but I don't understand exactly how to implement it.
extension Collection {
var indexedDictionary: [Int: Element] {
return enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }
}
}
so assuming I have an array of strings like
var someArray: [String] = ["String", "String", "String"...etc]
that I want to be indexed, making the end result being a dictionary like
[1: "string", 2: "string":..etc]
Using that method, how do I make that happen? Like where do I put the someArray into that code?
This extension:
extension Collection {
var indexedDictionary: [Int: Element] {
return enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }
}
}
adds the indexedDictionary
property to all Collection
s in Swift. An array is a Collection
, so arrays get this property added to them when you add this extension to a Swift source file at the top level (don't put it inside of another class
, struct
, or enum
). You only need to add this to one file in your project, and then the new property will be accessible in every file.
Then, you just call indexedDictionary
on any array in your code and it returns a Dictionary
of type [Int : Element]
where Element
represents the type in your original array. So, if your array called myArray
is of type [String]
, then myArray.indexedDictionary
will return a Dictionary
of type [Int : String]
.
Examples:
let arr1 = ["a", "b", "c"]
let dict1 = arr1.indexedDictionary
print(dict1)
Output:
[2: "c", 0: "a", 1: "b"]
// It works with dictionary literals
let dict2 = [5, 10, 15].indexedDictionary
print(dict2)
Output:
[2: 15, 0: 5, 1: 10]
let arr3: [Any] = [true, 1.2, "hello", 7]
print(arr3.indexedDictionary)
Output:
[2: "hello", 0: true, 1: 1.2, 3: 7]
Note: Dictionaries are unordered, so even though the order is unpredictable, the mapping of key to value is what you expect.