我有一个类簇——当我从 JSON 创建 Class
的实例时,我希望能够返回 Class
的子类。但是我似乎无法解决这些类型。
似乎 Subclass
的实例应该可以转换为 Class
。这里不是 Class
类型的 Self
吗?
帮助。
protocol JSONSerializable
{
static func withJSONRepresentation( json:Any? ) -> Self?
}
class Class : JSONSerializable
{
static func withJSONRepresentation( json:Any? ) -> Self?
{
return Subclass( jsonRepresentation: json )
}
init?( jsonRepresentation:Any? )
{
// init instance here
}
}
class Subclass : Class
{
override init?( jsonRepresentation:Any? )
{
// init instance here
}
}
最佳答案
这就是你想要的吗?我在返回中使用了 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(或类)实例,但是根据您的需要,您可能必须向下转换为所需的类型。
您现有代码的问题是编译器无法保证您会实现返回 Self
实例的 promise 。例如,当调用 Subclass.withJSONRepresentation
时,您的代码可能会返回 Class
的实例(或任何其他实例),这违反了 promise 。实际上这就是问题的症结所在 - 对于您当前的代码,如果 json 意味着它需要返回一个 Class
,您将不得不在 Class
static func 上调用它,而如果它应该返回一个 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))
关于swift - 在 Swift : "cannot convert return expression of type ' Subclass ?' to return type ' Self ?'" 中创建类集群(使用工厂方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35568919/