swift - 更改方法的协议(protocol)返回类型

标签 swift polymorphism protocols

我的协议(protocol)“模型”和符合“模型”的类“设备”有一些问题。 在我的协议(protocol)中,我有一个具有返回值“模型”的函数。在我的类(class)中,我有这个实现函数,并且想要将返回类型从“Model”更改为“Device”。但如果我改变这个,我必须再次添加原来的功能。

我的模型协议(protocol):

protocol Model {
    func fromJSON(jsonString : String) -> Model
}

我的设备类别:

class Device : Model {
    func fromJSON(jsonString: String) -> Model {
        var jsonObj = JSON(jsonString)
        var device = Device()
        return device
    }
}

当我尝试将此函数的结果分配给设备变量时,我收到以下错误消息:

Cannot assign a value of type "Model" to a value of type "Device"

let jsonString: String = "MY ARRAY";
var device2 = Device()
device2 = Device().fromJSON(jsonString)

最佳答案

您的模型协议(protocol)做出了 promise :

func fromJSON(jsonString : String) -> Model

它 promise 返回一些模型。它不 promise 返回与实现者相同类型的Model。如果你是这个意思,它就叫做Self

protocol Model {
    func fromJSON(jsonString : String) -> Self
}

对于类来说,实现起来有点困难。理想情况下,您的设备应该是一个结构,这使得它变得微不足道。但是如果你将类标记为final,那么也可以:

protocol Model {
    static func fromJSON(jsonString : String) -> Self
}

final class Device : Model {
    class func fromJSON(jsonString: String) -> Device {
        let device = Device()
        return device
    }
}

但实际上,整个协议(protocol)毫无意义。你真正想要的是一个初始化器:

protocol Model {
    init(jsonString : String)
}

class Device : Model {
    required init(jsonString: String) {
        ...
    }
}

关于swift - 更改方法的协议(protocol)返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30920443/

相关文章:

swift - 快速放置一个与屏幕相关的对象

ios - Swift:UITabbarController覆盖而不覆盖 Storyboard中的TabBar

swift - 运行脚本阶段错误 : framework is a directory

swift - 有没有办法在函数中使用通用协议(protocol)作为数据类型?

uitableview - Swift - 点击手势关闭键盘 UITableView

c++ - 具有 invoke_result 的重载命名非成员函数的返回类型

c++ - 智能指针作为多态性的类成员

java - Jackson - 反序列化为不同类型

ios - 在协议(protocol)定义的方法参数中调用的类的前向声明

ios - 如何在 Swift 中创建接口(interface)