Created
July 15, 2020 13:32
-
-
Save HarshilShah/a0a15eae52ab26e22a4e52e5287af49a to your computer and use it in GitHub Desktop.
A wrapper around PHFetchResult that conforms to various Swift sequence protocols
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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