Last active
March 9, 2021 14:12
-
-
Save Gujci/8307ab63bec7143486cab8dfa258acfd to your computer and use it in GitHub Desktop.
Wrapper to bridge realms auto updating behaviour with SwiftUIs value based immutability requirement. (Extract from https://stackoverflow.com/questions/57160790/index-out-of-bounds-when-using-realm-with-swiftui)
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 RealmSwift | |
typealias Model = Object & Identifiable | |
struct ListKey<T: Model>: Identifiable { | |
let id: T.ID | |
} | |
extension Results where Element: Model { | |
subscript(key: ListKey<Element>) -> Element? { | |
Element.primaryKey().flatMap { self.filter("\($0) = %@", key.id).first } | |
} | |
var keyedEnumeration: [ListKey<Element>] { | |
guard let key = Element.primaryKey() else { return [] } | |
let keys = value(forKey: key) as! [Element.ID] | |
return keys.enumerated().map { ListKey(id: $0.1) } | |
} | |
} |
An other hacky solution, to convert the List
to Results
with a simple filtering. As far as I know realm handles this very well, so not much performance is lost.
var keyedEnumeration: [ListKey<Element>] {
guard let key = Element.primaryKey() else { return [] }
let keys = filter("TRUEPREDICATE").value(forKey: key) as! [Element.ID]
return keys.enumerated().map { ListKey(id: $0.1) }
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@duncangroenewald that is because
RealmSwift.List
svalue(forKey: key)
is different from theResults
s. It returns[AnyObject]
instead ofAny
.let keys: [AnyObject] = value(forKey: key)
compiles but it requires a cast to occur later inreturn keys.enumerated().map { ListKey(id: $0.1) }
likeI have not tried whether it works or not. I suppose the key is usually a
String
orInt
, and none of them conforms toAnyObject
so this might crash.