1

我有一个类集群——当我Class从 JSON 创建一个实例时,我希望能够返回一个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
    }
}
4

1 回答 1

1

这就是你所追求的吗?我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))
于 2016-02-23T05:49:50.033 回答