Last active
September 16, 2021 14:16
-
-
Save ctreffs/785db636d68a211b25c989644b13f301 to your computer and use it in GitHub Desktop.
Array 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 array form a tuple. Given tuple's elements must have homogenous type. | |
| /// | |
| /// - Parameter tuple: a (homogenous) tuple | |
| /// - Returns: array of tuple elements | |
| func makeArray<Tuple, Value>(from tuple: Tuple) -> [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") | |
| func convert(child: Mirror.Child) -> Value? { | |
| 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))") | |
| return child.value as? Value | |
| } | |
| return tupleMirror.children.flatMap(convert) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example