0

I have a string array and I wish to convert to a Dictionary using the array index as the key in the Dictionary.

array = ["string1", "string2", "string3"]

convert to:

dictionary = [0 : "string1", 1 : "string2", 2 : "string3"]
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Roggie
  • 1,157
  • 3
  • 16
  • 40
  • `let dictionary = array.enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }` – Leo Dabus Sep 27 '18 at 02:50
  • you can also use Dictionary(uniqueKeysWithValues:) initializer and pass a new array from your array enumerated `let dictionary = Dictionary(uniqueKeysWithValues: Array(array.enumerated()))` – Leo Dabus Sep 27 '18 at 02:56
  • thanks Leo I appreciate your help, how can I cast the Dictionary to be [String : Any], your solution return [Int : String], I need the key of the Dictionary to be a String as this is being pushed up to Firebase DB and its throwing an error as its not expecting an Int as the Key – Roggie Sep 27 '18 at 02:59
  • `let dictionary = array.enumerated().reduce(into: [:]) { $0[String($1.offset)] = $1.element }` – Leo Dabus Sep 27 '18 at 03:02
  • Why do you want the value type to be Any if the array only contains strings? you should probably use `[String:String]` – Leo Dabus Sep 27 '18 at 03:04
  • If you really need [String:Any] you just need to cast the elements to Any `let dictionary = array.enumerated().reduce(into: [:]) { $0[String($1.offset)] = $1.element as Any }` – Leo Dabus Sep 27 '18 at 03:06
  • another approach to get `[String:String]` using the dictionary initialiser `let dict = Dictionary(uniqueKeysWithValues: array.enumerated().map{(String($0),$1)})` – Leo Dabus Sep 27 '18 at 03:11
  • for `[String:Any]` using the dictionary initialiser `let dict = Dictionary(uniqueKeysWithValues: array.enumerated().map{(String($0),$1 as Any)})` – Leo Dabus Sep 27 '18 at 03:12
  • thanks so much @LeoDabus this has really helped. The data its now in the format I need it to upload to Firebase DB - thanks again. – Roggie Sep 27 '18 at 03:12
  • I've updated the duplicated question link if you would like to check the extension now returns `[String:Element]` for Swift 4 as well – Leo Dabus Sep 27 '18 at 03:34

0 Answers0