gpt4 book ai didi

swift - 具有泛型和特化的协议(protocol)

转载 作者:可可西里 更新时间:2023-11-01 01:50:10 25 4
gpt4 key购买 nike

有没有一种方法可以在协议(protocol)中定义通用函数并允许符合规范的对象为该协议(protocol)定义特化?例如:

protocol Generic {
func generic<T>(prop: T, otherProp: String)
}

class Gen: Generic {
func generic<T>(prop: T, otherProp: String) {
print("generic")
}

func generic(prop: String, otherProp: String) {
print(prop)
}
}

现在如果我像这样使用这个类:

let inst = Gen()
inst.generic(prop: 1, otherProp: "Go")
inst.generic(prop: "Hello", otherProp: "Stop")

我得到了预期的结果:

generic
Hello

但是,如果我将 inst 声明为 Generic 类型:

let inst: Generic = Gen()
inst.generic(prop: 1, otherProp: "Go")
inst.generic(prop: "Hello", otherProp: "Stop")

我得到:

generic
generic

因此,如果我有一个类型为 Generic 的属性,我将无法使用协议(protocol)实现者对通用函数的特化。这是预期的行为吗?有没有办法实现我正在寻找的行为,即即使通过协议(protocol)接口(interface)访问也能使用通用函数的特化?我将不胜感激对此的任何见解。谢谢大家。

最佳答案

如果将协议(protocol)要求声明为泛型函数,则无法通过协议(protocol)类型调用同一函数的更特殊的重载版本。但是,您可以通过检查通用输入参数的类型来专门为您采用的类实现通用函数。

class Gen: Generic {
func generic<T>(prop: T, otherProp: String) {
if prop is String {
print(prop)
} else {
print("generic")
}
}
}

let inst: Generic = Gen()
inst.generic(prop: 1, otherProp: "Go")
inst.generic(prop: "Hello", otherProp: "Stop")

关于swift - 具有泛型和特化的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55148285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com