协议方法要求 - 符合类型允许方法参数为 replaced/overriden?

Protocol method requirement - allow method parameter to be replaced/overriden by conforming type?

我有一个协议 Device,其中包含所需的方法 makeACopy(device: Device) -> Device。当一个结构符合 Device 时,它应该指定自己来代替 Device.

现在,我想让我的 Phone 结构符合 Device。但是,当我使用 makeACopy(device: Phone) -> Phone 来满足 makeACopy(device: Device) -> Device 的要求时,我得到了这个错误:

Type 'Phone' does not conform to protocol 'Device'

这是我的代码:

protocol Device {
    var name: String { get set }
    func makeACopy(device: Device) -> Device
}

struct Phone: Device { /// Error: Type 'Phone' does not conform to protocol 'Device'
    var name = "My Phone"
    func makeACopy(device: Phone) -> Phone { /// my attempt to conform to `Device`'s method requirement
        return Phone(name: self.name)
    }
}

由于 Phone 符合 Device,我认为我的 makeACopy(device: Phone) -> Phone 方法会满足协议。但显然不是。

如何使 Devicefunc makeACopy(device: Device) -> Device 要求接受符合协议的 substitutes 参数?例如,将 device: Device 替换为 device: Phone?

听起来你在找这个,它保证输入和输出都是同一类型符合Device:

protocol Device {
    var name: String { get set }
    func makeACopy(device: Self) -> Self //<-- Note that `Self` is used instead of `Device`
}