Update:
The question voted to close this as duplicate deals with self.init()
which can be solved by marking class final or requiring init. But How does that work on Repositories or return from any other method other than init
(My Implementation is @NSManaged Object)
Here is what I want to do. Get a JSON Via Request, then parse it into an object.
var req = Request("http://somewhere/story/get/1")
var story = req.parseJsonResponse() as Story
The Request
class somehow looks like this:
class Request {
public var httpJsonResponse : String
init(_ url : String) {
//This comes from HTTP
httpJsonResponse = "{}"
}
public func parseJsonResponse<T : IParse>() -> T {
return T.parse(json: httpJsonResponse)
}
}
Now, I want to make sure that IParse
implementation has parse method:
protocol IParse {
static func parse(json : String) -> Self
}
So far so good, here's the problem with implementation:
class Story : IParse {
required init()
{
}
public static func parse(json: String) -> Self
{
//return self.init() works thanks to @tomahh
return StoryRepo.ById(1)
}
}
class StoryRepo {
public static func ById(_ id : Int) -> Story {
return Story()
}
}
This does not work. Neither of these work:
- Returning Story
- Casting
Story() as! Self
See updated playground gist.