Create a Swift Dictionary from an Array

Here is a Gist I posted showing a Swift utility function that enables you to create a Dictionary containing an optional entry for every element in an Array. It uses the reduce function to create one Dictionary from every element in an Array, based on a closure you provide that turns an array element into a key-value tuple.

This code was compiled and tested against Xcode 6 Beta 3.

Creates a dictionary with an optional
entry for every element in an array.
func toDictionary<E, K, V>(
array: [E],
transformer: (element: E) -> (key: K, value: V)?)
-> Dictionary<K, V>
return array.reduce([:]) {
(var dict, e) in
if let (key, value) = transformer(element: e)
dict[key] = value
return dict
struct Person
let name: String
let age: Int
let people = [
Person(name: "Billy", age: 42),
Person(name: "David", age: 24),
Person(name: "Maria", age: 99)]
let dictionary = toDictionary(people) { ($, $0.age) }
// Prints: [Billy: 42, David: 24, Maria: 99]

This entry was posted in Swift and tagged , , . Bookmark the permalink.

2 Responses to Create a Swift Dictionary from an Array

  1. Jessy says:

    I don’t think we should be creating this kind of thing for specific structs and classes; instead let’s make this an instance method of a protocol, and extend Array to implement it, as with C#:

    • Josh Smith says:

      Let me know when you put together a sample of this, I’m curious to see your approach.

Comments are closed.