Can't use anything other than default.realm with SwiftUI

Touching Realm before setting up a config for it will cause it to create the default.realm file and then after you set up the config, create the debug.realm file.

How is realm instantiated or used before this line?

realm = try! Realm(configuration: realmConfig)

Are you using it anywhere else? Did you define a migration or attempt to do anything with it before that line?


Best practice is this

var realm = try! Realm()
var realmConfig = Realm.Configuration.defaultConfiguration

realm = try! Realm(configuration: realmConfig)


or, go with a singleton shared service approach - this uses a realm file on the desktop

class RealmService {
    private init() {}

    static let shared = RealmService()

    lazy var realm: Realm = {
        let manager = FileManager()
        let homeURL = manager.homeDirectoryForCurrentUser
        let desktopURL = homeURL.appendingPathComponent("Desktop")
        let pathToThisRealmFile = desktopURL.appendingPathComponent("desktopRealm.realm")

        var config = Realm.Configuration.defaultConfiguration
        config.fileURL = pathToThisRealmFile
        let realm = try! Realm.init(configuration: config)
        return realm
    }()
}

then to use

let realm = RealmService.shared.realm


or the old classic global function (I start my global functions with a 'g"). This uses a Realm in My Dropbox/Development folder inside the My Realm Project folder.

func gGetRealm() -> Realm? {
    do {
        let manager = FileManager()
        let homeFolder = manager.homeDirectoryForCurrentUser
        let pathToThisFolder = homeFolder.appendingPathComponent("Dropbox/Development/My Realm Project")
        let pathToThisRealmFile = pathToThisFolder.appendingPathComponent("default.realm")

        var config = Realm.Configuration.defaultConfiguration
        config.fileURL = pathToThisRealmFile
        let realm = try Realm.init(configuration: config)
        return realm

    } catch let error as NSError {
        print("Error!")
        print("  " + error.localizedDescription + "  " + String(error.code) )
        return nil
    }
}
if let maybeRealm = gGetRealm() {
   //do something with maybeRealm
}

In any of the above, note that nothing is being done with Realm until it’s ready to be used. '=Realm.init(....

2 Likes