这就是你所追求的吗?我self.init
在退货中使用,因此需要一个required init
.
protocol JSONSerializable
{
static func withJSONRepresentation( json:Any? ) -> Self?
}
class Class : JSONSerializable
{
static func withJSONRepresentation( json:Any? ) -> Self?
{
return self.init( jsonRepresentation: json )
}
required init( jsonRepresentation:Any? )
{
}
}
class Subclass : Class
{
required init( jsonRepresentation:Any? )
{
super.init(jsonRepresentation: jsonRepresentation)
}
}
print(Class.withJSONRepresentation(nil)) // -> Class
print(Subclass.withJSONRepresentation(nil)) // -> Subclass
编辑:
另一种方法是返回 JSONSerializable(或 Class)实例,但是根据您的需要,您可能必须向下转换为所需的类型。
您现有代码的问题是编译器无法保证您会履行返回Self
. 例如,当调用 时Subclass.withJSONRepresentation
,您的代码可能会返回Class
(或其他任何内容)的实例,这会破坏承诺。实际上这是问题的症结所在 - 对于您当前的代码,如果 json 意味着它需要返回 a Class
,则必须在Class
静态 func 上调用它,而如果它应该返回 a Subclass
,则必须在Subclass
静态函数 “Self”不包括子类,所以如果在Class
静态函数上调用,它必须只返回一个Class
实例,而不是子类。
protocol JSONSerializable
{
static func withJSONRepresentation( json:Any? ) -> JSONSerializable?
}
class Class : JSONSerializable
{
static func withJSONRepresentation( json:Any? ) -> JSONSerializable?
{
return Subclass( jsonRepresentation: json )
}
init?( jsonRepresentation:Any? )
{
// init instance here
}
}
class Subclass : Class
{
}
print(Class.withJSONRepresentation(nil))