Convert Swift Array to Dictionary With Indexes

Convert Swift Array to Dictionary with indexes

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)})
}
}

Array from dictionary keys in swift

Swift 3 & Swift 4

componentArray = Array(dict.keys) // for Dictionary

componentArray = dict.allKeys // for NSDictionary

Swift 3: Array to Dictionary?

I think you're looking for something like this:

extension Array {
public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
var dict = [Key:Element]()
for element in self {
dict[selectKey(element)] = element
}
return dict
}
}

You can now do:

struct Person {
var name: String
var surname: String
var identifier: String
}

let arr = [Person(name: "John", surname: "Doe", identifier: "JOD"),
Person(name: "Jane", surname: "Doe", identifier: "JAD")]
let dict = arr.toDictionary { $0.identifier }

print(dict) // Result: ["JAD": Person(name: "Jane", surname: "Doe", identifier: "JAD"), "JOD": Person(name: "John", surname: "Doe", identifier: "JOD")]

If you'd like your code to be more general, you could even add this extension on Sequence instead of Array:

extension Sequence {
public func toDictionary<Key: Hashable>(with selectKey: (Iterator.Element) -> Key) -> [Key:Iterator.Element] {
var dict: [Key:Iterator.Element] = [:]
for element in self {
dict[selectKey(element)] = element
}
return dict
}
}

Do note, that this causes the Sequence to be iterated over and could have side effects in some cases.

Turning an indexed array into a dictionary in Swift

This extension:

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

adds the indexedDictionary property to all Collections 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.

How do I convert data dictionary into an array Swift?

About using map, I guess this page is helpful and visual.

let names = data.map { return $0.key }
print(names) // prints ["café-veritas", "cafe-myriade"]

Convert Swift Array to Dictionary with indexes

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)})
}
}

Create Dictionary from Array in Swift 5

You can do a map, and then individually change the type of the first dictionary:

var dicts = urlArray.map { ["name": $0, "type": "B"] }
dicts[0]["type"] = "A"

Seeing how all your dictionary keys are all the same, and that you are sending this to a server, a Codable struct might be a better choice.

struct NameThisProperly : Codable {
var name: String
var type: String
}

var result = urlArray.map { NameThisProperly(name: $0, type: "B") }
result[0].type = "A"
do {
let data = try JSONDecoder().encode(result)
// you can now send this data to server
} catch let error {
...
}

Swift 2 - Separating an array into a dictionary with keys from A to Z

Using only Swift 2 objects and methods, and with a key for each letter in the alphabet:

let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.map({ String($0) })

let words = ["Apple", "Banana", "Blueberry", "Eggplant"]

var result = [String:[String]]()

for letter in alphabet {
result[letter] = []
let matches = words.filter({ $0.hasPrefix(letter) })
if !matches.isEmpty {
for word in matches {
result[letter]?.append(word)
}
}
}

print(result)


Related Topics



Leave a reply



Submit