Skip to content

Instantly share code, notes, and snippets.

@ctreffs
Last active September 16, 2021 14:16
Show Gist options
  • Select an option

  • Save ctreffs/785db636d68a211b25c989644b13f301 to your computer and use it in GitHub Desktop.

Select an option

Save ctreffs/785db636d68a211b25c989644b13f301 to your computer and use it in GitHub Desktop.
Array from Tuple [Swift]
/// 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)
}
@ctreffs

ctreffs commented Oct 5, 2017

Copy link
Copy Markdown
Author

Example

let stringTuple = ("A", bLabel: "B", "C", "D", "E")
let stringArray: [String] = makeArray(from: stringTuple)
// ["A", "B", "C", "D", "E"]

let intTuple = (1, 2, 3, 4)
let intArray: [Int] = makeArray(from: intTuple)
// [1, 2, 3, 4]

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