0

When I try to instantiate a class through "static" method (required from protocol), the compiler don't recognize the initializer, although I pass correct parameters.

enter image description here

enter image description here

2
  • how is User defined? or more specifically, what does it's initializer look like? Commented Jul 27, 2014 at 1:12
  • is a empty class, has no propertie or initializer @drewag. even if I remove author and Interaction superclass it will fail Commented Jul 27, 2014 at 1:18

1 Answer 1

1

The problem is that you are defining a template called "Comment" in your method declaration that is obscuring the real Comment class. You need to give that template argument a different name.

And I believe your JSONSerializable protocol is not defined the way you want it. You can use Self in a protocol to refer to the class implementing the protocol so there is no need for a template. Your protocol could look like this:

protocol JSONSerializable {
    class func instanceFrom(json: [String:AnyObject]) -> Self;
}

Then you would implement this method in your Comment class:

class Comment: JSONSerializable {
    ...

    class func instanceFrom(json: [String:AnyObject]) -> Comment {
        return Comment(message: "lorem lorem", author: User())
    }
}

However, it is preferred in Swift to use initializers instead of class methods:

protocol JSONSerializable {
    init(json: [String:AnyObject])
}

class Comment: JSONSerializable {
    ...

    init(json: [String : AnyObject]) {
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

perfect! I believe that I'm still thinking Java Generics and tried to apply the same concept here. I don't knew Self. thanks!
I don't use initializers because instanceFrom is a specific builder method. I could extract it to extension class, I don't know.. This type can be created from other source (sqlite, by hands or Realm lib) too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.