When writing Swift apps with the Realm Mobile Platform, you’d probably run into writing something like following a lot.

1
2
3
4
let syncConfig = SyncConfiguration(
user: SyncUser.current!,
realmURL: URL(string: "realm://localhost:9080/~/myRealm")!)
let realm = try! Realm(configuration: Realm.Configuration(syncConfiguration: syncConfig))

Extension Method to the Rescue!!

Well let’s keep things DRY (Don’t Repeat Yourself). Copy and paste this little snippet in your apps.

1
2
3
4
5
6
7
8
9
10
11
12
13
import RealmSwift
extension Realm {
convenience init(urlString: String) throws {
let syncConfig = SyncConfiguration(
user: SyncUser.current!,
realmURL: URL(string: urlString)!)
try self.init(configuration: Realm.Configuration(syncConfiguration: syncConfig))
}
}

Now you can just do this all over your app!!!

1
let realm = try! Realm(urlString: "realm://localhost:9080/~/myRealm")

Considerations

  • This just a gist that constructs the simplest synced Realm with the current user. So take care that your user is already authenticated.
  • Remember, the url string is the full realm:// or realms:// URL string not a path!. So you can’t supply ~/myRealm

Of course there are other fancier ways to construct this but extension methods can keep things quite neat! Enjoy!