webmagnets
webmagnets

Reputation: 2306

How do I fix this error?: "use of unimplemented initializer 'init()' for class"

Here is my class:

class Sentence: RLMObject {
    dynamic var words = RLMArray(objectClassName: Word.className())
    dynamic var content = ""

    init(content: String){
        super.init(object: content)
        self.content = content
        let wordArray = makeWordTokens(content)
    }

When I try to create a Sentence object like this...

let sentence = Sentence(content: "你好吗?")

...I get the following runtime error:

fatal error: use of unimplemented initializer 'init()' for class 'MyApp.Sentence'

Why does it tell me I haven't implemented the initializer? What should I do to fix this?

Upvotes: 1

Views: 2059

Answers (2)

jpsim
jpsim

Reputation: 14409

init() must be implemented when creating Realm models in Swift. This is because Realm uses Swift's reflect() for introspection to determine what properties are in your models, which requires Realm to create an instance of your model.

Simply creating an empty init() should work fine.

There's also the matter of no providing an appropriate object argument to super.init(object:). The RLMObject(object:) initializer expects the object argument to be either an array or dictionary of properties to set. In your case, you're passing it a String.

Upvotes: 2

rintaro
rintaro

Reputation: 51911

When you implement designated initializer, subclass doesn't inherit superclass designated initializers. see the docs.

RLMObject's init(object:) calls self.init():

- (instancetype)initWithObject:(id)value {
    self = [self init];

but Sentence does not inherits init() initializer. That's why you see the error.

I think convenience initializer solves your problem:

class Sentence: RLMObject {

    convenience init(content: String){
//  ^^^^^^^^^^^^
        self.init(object: content)
//      ^^^^^

        ...
    }

    ...
}

Upvotes: 2

Related Questions