Skip to content

Instantly share code, notes, and snippets.

@HarshilShah
Created July 15, 2020 13:32
Show Gist options
  • Save HarshilShah/a0a15eae52ab26e22a4e52e5287af49a to your computer and use it in GitHub Desktop.
Save HarshilShah/a0a15eae52ab26e22a4e52e5287af49a to your computer and use it in GitHub Desktop.
A wrapper around PHFetchResult that conforms to various Swift sequence protocols
import Photos
final class FetchResult<Object: AnyObject> {
let phFetchResult: PHFetchResult<Object>
init(_ phFetchResult: PHFetchResult<Object>) {
self.phFetchResult = phFetchResult
}
}
extension FetchResult: Sequence {
typealias Iterator = AnyIterator<Object>
typealias Element = Object
func makeIterator() -> Iterator {
var count = 0
return AnyIterator<Object> {
defer { count += 1 }
if count < self.phFetchResult.count {
return self.phFetchResult.object(at: count)
} else {
return nil
}
}
}
}
extension FetchResult: Collection {
typealias Index = Int
var startIndex: Int { 0 }
var endIndex: Int { phFetchResult.count }
func index(after i: Int) -> Int { i + 1 }
subscript(position: Int) -> Object {
phFetchResult.object(at: position)
}
subscript(bounds: IndexSet) -> [Object] {
phFetchResult.objects(at: bounds)
}
}
extension FetchResult: BidirectionalCollection {
func index(before i: Int) -> Int { i - 1 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment