DCDC DCDC - 7 months ago 25
Swift Question

RealmSwift initializers - Xcode fix-it keeps getting it wrong

I cannot get Realm working when I want to provide initializer for a class, Xcode endlessly suggest errors.

I decided to upload two screenshots instead of code snippet to make it easier to see errors

enter image description here

I follow the suggestions and end up with this

enter image description here

The last error tells "Use of undeclared type 'RLMObjectSchema'

I use the latest 0.99 version of RealmSwift

Answer

The recommended way is creating memberwise convenience initializer, like the following:

class Item: Object {
    dynamic var isBook: Bool = true
    dynamic var numberOfPages: Double = 0
    dynamic var isInForeignLanguage: Bool = true
    dynamic var isFictional: Bool = true
    dynamic var value: Int {
        get {
            return calculalatedValue()
        }
    }

    convenience init(isBook: Bool, numberOfPages: Double, isInForeignLanguage: Bool, isFictional: Bool) {
        self.init()
        self.isBook = isBook
        self.numberOfPages = numberOfPages
        self.isInForeignLanguage = isInForeignLanguage
        self.isFictional = isFictional
    }

    ...
}

You cannot omit default initializer because Realm needs default initializer for instantiating objects for querying. When querying to the Realm, Realm calls default initializer internally to instantiate the objects.

You can also override default initializer, but we don't recommend it. Because when you override the default initializer, you should override other required initializers inherited from ObjC layer due to Swift type system limitation. Also you should import both Realm and RealmSwift frameworks. Because there are Objective-C only class in the parameters of those initializers.

import RealmSwift
import Realm // Need to add import if you override default initializer!

class Item: Object {
    dynamic var isBook: Bool = true
    dynamic var numberOfPages: Double = 0
    dynamic var isInForeignLanguage: Bool = true
    dynamic var isFictional: Bool = true
    dynamic var value: Int {
        get {
            return calculalatedValue()
        }
    }

    required init() {
        super.init()
    }

    required init(realm: RLMRealm, schema: RLMObjectSchema) {
        super.init(realm: realm, schema: schema)
    }

    required init(value: AnyObject, schema: RLMSchema) {
        super.init(value: value, schema: schema)
    }
Comments