Skip to content

Instantly share code, notes, and snippets.

@TJRoger
Forked from emctague/TupleToArray.swift
Created July 4, 2020 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TJRoger/236179523c84bee696660da4c1eeca9c to your computer and use it in GitHub Desktop.
Save TJRoger/236179523c84bee696660da4c1eeca9c to your computer and use it in GitHub Desktop.
Tuple to Array Conversion for Swift
/**
# Tuple-to-array for Swift
By Ethan McTague - January 28, 2020
This source code is in the public domain.
## Example
To convert a tuple of Ints into an array of ints:
```
let ints = (10, 20, 30)
let result = [Int].fromTuple(ints)
print(result!) // prints Optional([10, 20, 30])
```
*/
import Cocoa
extension Array {
/**
Attempt to convert a tuple into an Array.
- Parameter tuple: The tuple to try and convert. All members must be of the same type.
- Returns: An array of the tuple's values, or `nil` if any tuple members do not match the `Element` type of this array.
*/
static func fromTuple<Tuple> (_ tuple: Tuple) -> [Element]? {
let val = Array<Element>.fromTupleOptional(tuple)
return val.allSatisfy({ $0 != nil }) ? val.map { $0! } : nil
}
/**
Convert a tuple into an array.
- Parameter tuple: The tuple to try and convert.
- Returns: An array of the tuple's values, with `nil` for any values that could not be cast to the `Element` type of this array.
*/
static func fromTupleOptional<Tuple> (_ tuple: Tuple) -> [Element?] {
return Mirror(reflecting: tuple)
.children
.filter { child in
(child.label ?? "x").allSatisfy { char in ".1234567890".contains(char) }
}.map { $0.value as? Element }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment