Skip to content

Instantly share code, notes, and snippets.

@TJRoger
Forked from emctague/TupleToArray.swift
Created July 4, 2020 09:30
Show Gist options
  • Save TJRoger/236179523c84bee696660da4c1eeca9c to your computer and use it in GitHub Desktop.
Save TJRoger/236179523c84bee696660da4c1eeca9c to your computer and use it in GitHub Desktop.

Revisions

  1. @emctague emctague created this gist Jan 29, 2020.
    47 changes: 47 additions & 0 deletions TupleToArray.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    /**
    # 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 }
    }
    }