Search code examples
swiftmacosrealm

SwiftRealm optional value with default


I am very new to Realm but I was wondering if there was a way to set the default of an optional value to another variable. I know this sounds very confusing but I hope my code will explain it. My goal is to create Directories with multiple categories. If the user does not enter a custom for the category, it will default to the last path component (folder name). Does anyone have any ideas about how to do this? I was thinking about doing @objc dynamic var name: String = (path as NSString).lastPathComponent but it wouldn't work. Any help is appreciated. Thanks!

    class Category: Object {
    let name = (LinkingObjects(fromType: Category.self, property: "path") as NSString).lastPathComponent
    @objc dynamic var path = ""
    @objc dynamic var directory: Directory?
}


class Directory: Object {
    @objc dynamic var name = ""
    @objc dynamic var path = ""
    let categories = List<Category>()
}

Solution

  • This is not a Realm issue, but a Swift issue in general. You cannot declare an instance property and assign it a value in which you are referring to the value of another instance property, since instance properties are only guaranteed to have a value at the end of the initializer, but when you declare an instance property with a default value, that gets called before the initializer, so there's no guarantee that the other properties already have values.

    If you need name to be a persisted Realm property, you won't be able to use your other instance property to get a default value, however, if you don't need to persist name in Realm, you can simply make name a lazy variable and hence you'll be able to access other instance properties.

    lazy var name = (path as NSString).lastPathComponent