Skip to content

Instantly share code, notes, and snippets.

@karwa
Last active July 9, 2018 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karwa/e4c8f637345407f2f56bac9540d8f9c8 to your computer and use it in GitHub Desktop.
Save karwa/e4c8f637345407f2f56bac9540d8f9c8 to your computer and use it in GitHub Desktop.
unzip collection
/// Provides a view of a collection of tuples as multiple collections.
public func unzip<C, TA, TB>(_ collection: C) -> Unzip2Collection<C, TA, TB> where C: Collection {
return Unzip2Collection(collection)
}
/// Provides a view of a collection of tuples as multiple collections.
public struct Unzip2Collection<C, TupleA, TupleB> where C: Collection, C.Iterator.Element == (TupleA, TupleB) {
private let _col: C
public init(_ c: C) { _col = c }
public struct FirstCollection: Collection {
fileprivate let _col: C
public var count: Int { return _col.count }
public var startIndex: C.Index { return _col.startIndex }
public var endIndex: C.Index { return _col.endIndex }
public func index(after i: C.Index) -> C.Index { return _col.index(after: i) }
public func index(_ i: C.Index, offsetBy n: Int) -> C.Index { return _col.index(i, offsetBy: n) }
public subscript(index: C.Index) -> TupleA { return _col[index].0 }
}
public struct SecondCollection: Collection {
fileprivate let _col: C
public var count: Int { return _col.count }
public var startIndex: C.Index { return _col.startIndex }
public var endIndex: C.Index { return _col.endIndex }
public func index(after i: C.Index) -> C.Index { return _col.index(after: i) }
public func index(_ i: C.Index, offsetBy n: Int) -> C.Index { return _col.index(i, offsetBy: n) }
public subscript(index: C.Index) -> TupleB { return _col[index].1 }
}
public var first: FirstCollection { return FirstCollection(_col: _col) }
public var second: SecondCollection { return SecondCollection(_col: _col) }
}
extension Unzip2Collection.FirstCollection: BidirectionalCollection where C: BidirectionalCollection {
public func index(before i: C.Index) -> C.Index {
return _col.index(before: i)
}
}
extension Unzip2Collection.SecondCollection: BidirectionalCollection where C: BidirectionalCollection {
public func index(before i: C.Index) -> C.Index {
return _col.index(before: i)
}
}
extension Unzip2Collection.FirstCollection: RandomAccessCollection where C: RandomAccessCollection {
}
extension Unzip2Collection.SecondCollection: RandomAccessCollection where C: RandomAccessCollection {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment