Tuples.swift
Generic Tuple types for Swift
Why?
Swift doesn't support generics for tuples. They can't be properly used in the where
clauses.
This library provides set of tuple-like structs and helper protocols to fix this.
Getting started
Installation
Package Manager
Add the following dependency to your Package.swift:
.package(url: "https://github.com/tesseract-one/Tuples.swift.git", from: "0.1.0")
Run swift build
and build your app.
CocoaPods
Add the following to your Podfile:
pod 'Tuples', '~> 0.1.0'
Then run pod install
Examples
Accept tuple as generic parameter
func accept_tuple<T>(tuple: T.STuple) where T: SomeTuple2, T.T1: StringProtocol, T.T2: UnsignedInteger {
// tuple is (StringProtocol, UnsignedInteger)
// tuple struct can be created
let tupleStruct = T(tuple)
}
Common constructor method
// Will create Tuple4<Int, String, Double, Array<Int>> instance
let tupleStruct = T_((1, "string", 2.0, [1, 2, 3]))
Tuple from array
// Tuple3<Int, Int, Int> returned but typed as OneTypeTuple<Int>
let tuple: OneTypeTuple<Int> = T_([1, 2, 3])
Codable
Tuples can be encoded / decoded as arrays.
let json = try! JSONEncoder().encode(T_((1, "string", Data())))
let tuple = try JSONDecodder().decode(Tuple3<Int, String, Data>.self, from: json).tuple
List tuples
All tuples with 1+ elements supports ListTuple
protocol which allows to get first and last elements from the tuple and also suffix and prefix tuples without this elements.
public protocol ListTuple: SomeTuple {
associatedtype First
associatedtype Last
associatedtype DroppedFirst: SomeTuple
associatedtype DroppedLast: SomeTuple
init(first: DroppedLast, last: Last)
init(first: First, last: DroppedFirst)
var first: First { get }
var last: Last { get }
var dropLast: DroppedLast { get }
var dropFirst: DroppedFirst { get }
}
Usage examples can be found in the Codable and CustomStringConvertible implementations
Author
License
Tuples.swift is available under the Apache 2.0 license. See the LICENSE file for more information.