swift - 在 Swift : "cannot convert return expression of type ' Subclass ?' to return type ' Self ?'" 中创建类集群(使用工厂方法)

标签 swift swift-protocols

我有一个类簇——当我从 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/

相关文章:

protocols - 在 Swift 中默认实现协议(protocol)时,实现默认属性的正确方法是什么?

macos - 单击 statusItem 时如何调用函数/操作?

ios - 重复的对象被追加到数组 swift firebase 中

swift - Date() 总是初始化 UTC 日期吗?

ios - 以编程方式在 UIView 上添加 UITextField Swift

ios - 当它是一个单独的 Swift 文件时,从 TableViewDataSource 中删除或添加单元格

swift - 动态调度协议(protocol)扩展不适用于多个目标

swift - 枚举符合具有存储属性的协议(protocol)

swift - 为什么协议(protocol)中的仅获取属性要求不能通过符合的属性来满足?

swift 。 UIKit 中委托(delegate)模式的协议(protocol)。 NSObject协议(protocol)