Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Boxing up AnyRealmCollection
// 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
}
@prohoney

This comment has been minimized.

Copy link

commented Feb 21, 2019

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.