Created
February 19, 2019 15:17
-
-
Save rnapier/37aa8996e767730e0d96a7ef9b74a865 to your computer and use it in GitHub Desktop.
Boxing up AnyRealmCollection
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
// https://stackoverflow.com/questions/54764362/swift-array-of-tuples-with-generic-tuple-elements/54768030 | |
struct AnyRealmCollectionBox<Element> { | |
public func index(after i: Int) -> Int { return i + 1 } | |
public func index(before i: Int) -> Int { return i - 1 } | |
private let _realm: () -> Realm? | |
public var realm: Realm? { return _realm() } | |
private let _isInvalidated: () -> Bool | |
public var isInvalidated: Bool { return _isInvalidated() } | |
private let _count: () -> Int | |
public var count: Int { return _count() } | |
private let _description: () -> String | |
public var description: String { return _description() } | |
private let _indexOf: (Element) -> Int? | |
public func index(of object: Element) -> Int? { return _indexOf(object) } | |
private let _indexMatching: (NSPredicate) -> Int? | |
public func index(matching predicate: NSPredicate) -> Int? { return _indexMatching(predicate) } | |
// ... | |
} | |
extension AnyRealmCollectionBox where Element: RealmCollectionValue { | |
init(_ collection: AnyRealmCollection<Element>) { | |
_realm = { collection.realm } | |
_isInvalidated = { collection.isInvalidated } | |
_count = { collection.count } | |
_description = { collection.description } | |
_indexOf = { collection.index(of: $0) } | |
_indexMatching = { collection.index(matching: $0) } | |
//... | |
} | |
} | |
struct Model<Element> { | |
// 1. a String field | |
let string: String | |
// 2. either an Array<SomeElement>, or AnyRealmCollection<SomeObject> | |
enum Container { | |
case array([Element]) | |
case realmCollection(AnyRealmCollectionBox<Element>) | |
} | |
let elements: [Container] | |
// 3. a closure that acts upon the specific SomeElement or SomeObject. | |
let process: (Element) -> Void | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm starting to write my own gists and was looking into your gists for inspiration.
The idea to link a related stackoverflow link is smart. Any other suggestions when it comes to writing gists?