8000 GitHub - tesseract-one/Tuples.swift: Generic Tuple types for Swift
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

tesseract-one/Tuples.swift

Repository files navigation

Tuples.swift

🐧 linux: ready GitHub license Build Status GitHub release SPM compatible CocoaPods version Platform OS X | iOS | tvOS | watchOS | Linux

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

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.

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 = TL((1, "string", 2.0, [1, 2, 3]))

Tuple from array

 // Tuple3<Int, Int, Int> returned but typed as OneTypeTuple<Int>
let tuple: OneTypeTuple<Int> = TL([1, 2, 3])

Codable

Tuples can be encoded / decoded as arrays.

let json = try! JSONEncoder().encode(TL((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.

About

Generic Tuple types for Swift

Resources

License

Stars

Watchers

Forks

Packages

No packages published
0