Skip to content

Instantly share code, notes, and snippets.

@ctreffs
Created October 5, 2017 09:28
Show Gist options
  • Save ctreffs/cbba9e919a809f31d35cba6302bffa8b to your computer and use it in GitHub Desktop.
Save ctreffs/cbba9e919a809f31d35cba6302bffa8b to your computer and use it in GitHub Desktop.
Dictionary from Tuple [Swift]
/// Generates dictionary from a tuple. Given tuple's elements must have homogenous type.
///
/// - Parameter tuple: a (homogenous) tuple
/// - Returns: dict of tuple elements
func makeDictionary<Tuple, Value>(from tuple: Tuple) -> [String:Value] {
let tupleMirror = Mirror(reflecting: tuple)
assert(tupleMirror.displayStyle == .tuple, "Given argument is no tuple")
assert(tupleMirror.superclassMirror == nil, "Given tuple argument must not have a superclass (is: \(tupleMirror.superclassMirror!)")
assert(!tupleMirror.children.isEmpty, "Given tuple argument has no value elements")
let count: Int = tupleMirror.children.underestimatedCount
var dict: [String:Value] = [String:Value](minimumCapacity: count)
func convert(child: Mirror.Child) -> Void {
let valueMirror = Mirror(reflecting: child.value)
assert(valueMirror.subjectType == Value.self, "Given tuple argument's child type (\(valueMirror.subjectType)) does not reflect expected return value type (\(Value.self))")
let key: String = child.label! // tuples always have lables
dict[key] = child.value as? Value
}
tupleMirror.children.forEach(convert)
return dict
}
@ctreffs
Copy link
Author

ctreffs commented Oct 5, 2017

Example

let stringTuple = ("A", bLabel: "B", "C", "D", "E")
let stringDict: [String:String] = makeDictionary(from: stringTuple)
// ["bLabel": "B", ".3": "D", ".4": "E", ".0": "A", ".2": "C"]

let intTuple = (1, 2, 3, 4)
let intDict: [String:Int] = makeDictionary(from: intTuple)
// [".3": 4, ".1": 2, ".2": 3, ".0": 1]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment