-
-
Save TJRoger/236179523c84bee696660da4c1eeca9c to your computer and use it in GitHub Desktop.
Revisions
-
emctague created this gist
Jan 29, 2020 .There are no files selected for viewing
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 charactersOriginal 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 } } }