Brynjar Brynjar - 7 months ago 13
Swift Question

Is the Realm method addOrUpdateObject() callable from Swift?

According to the docs; https://realm.io/docs/objc/latest/api/Classes/RLMRealm.html the method

- (void)addOrUpdateObject:(nonnull RLMObject *)object

is available via Obj-C

The Swift docs; https://realm.io/docs/swift/latest/api/Classes/Realm.html don't mention this method.

In my Swift app, if I try and call this method
self.realm!.addOrUpdateObject(model)
then I get a compiler error
Value of type 'Realm' has no member 'addOrUpdateObject'


Yet I see other places online, e.g. How to properly map JSON properties to model properties in Realm.create where people are apparently using it from Swift.

I am using Realm via cocoapods - pod 'RealmSwift' - which brings down 2 pods; Realm and RealmSwift. I can see this method defined in RLMRealm.mm I tried adding
#import <Realm/Realm.h>
to my bridging header but that didn't work.

How do I call this method from Swift?

Answer

This is available in Swift, and is defined as:

public func add(object: Object, update: Bool = false)

So to get the same behaviour as the Obj-C Realm's method, you'd call it:

self.realm!.add(model, update: true)