Created
October 5, 2017 09:28
-
-
Save ctreffs/cbba9e919a809f31d35cba6302bffa8b to your computer and use it in GitHub Desktop.
Dictionary from Tuple [Swift]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example