元组 0.1.3

Tuples 0.1.3

Yehor Popovych 维护。



Tuples 0.1.3

  • Tesseract Systems, Inc.

Tuples.swift

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

Swift 中的泛型元组类型

为什么?

Swift 不支持元组的泛型。它们不能在 where 子句中正确使用。

这个库提供了一套类似元组的结构体和辅助协议来解决此问题。

入门

安装

包管理器

将以下依赖项添加到您的Package.swift

.package(url: "https://github.com/tesseract-one/Tuples.swift.git", from: "0.1.0")

运行 swift build并构建您的应用程序。

CocoaPods

将以下内容添加到您的Podfile

pod 'Tuples', '~> 0.1.0'

然后运行 pod install

示例

将元组作为泛型参数接受

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)
}

公共构造方法

// Will create Tuple4<Int, String, Double, Array<Int>> instance
let tupleStruct = T_((1, "string", 2.0, [1, 2, 3]))

从数组中创建元组

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

Codable

元组可以作为数组进行编码/解码。

let json = try! JSONEncoder().encode(T_((1, "string", Data())))
let tuple = try JSONDecodder().decode(Tuple3<Int, String, Data>.self, from: json).tuple

列表元组

所有包含1个或多个元素的元组都支持ListTuple协议,该协议允许从元组中获取第一个和最后一个元素,并且可以获取不包含这些元素的元组后缀和前缀。

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 }
}

使用示例可以在CodableCustomStringConvertible实现中找到。

作者

许可协议

Tuples.swift 可在 Apache 2.0 许可协议下使用。更多信息请参阅LICENSE 文件