Skip to content

Instantly share code, notes, and snippets.

@rnapier
Created February 19, 2019 15:17
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 rnapier/37aa8996e767730e0d96a7ef9b74a865 to your computer and use it in GitHub Desktop.
Save rnapier/37aa8996e767730e0d96a7ef9b74a865 to your computer and use it in GitHub Desktop.
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
}
@mfaani
Copy link

mfaani 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