[英]return protocol with associated type
如何返回关联类型的协议?
protocol AProtocol {
}
class A: AProtocol {
}
class Main {
func sendA() -> AProtocol {
return A()
}
}
有用。
但
protocol BProtocol {
associatedtype B
}
class B: BProtocol {
typealias B = Int
}
class Main {
func sendA() -> AProtocol {
return A()
}
func sendB() -> BProtocol { // error
return B()
}
// function1
func sendB_<T: BProtocol>() -> T{
return B() as! T
}
}
我想在函数1中返回'return B()'吗?
您试图在情况1中返回BProtocol
。问题是PAT(具有关联类型的协议) 不是完全类型。 它们充当类型的占位符。 因此,您不能直接返回BProtocol
。
迅捷5.1
我不确定100%,但是我认为在swift(5.1)的下一个迭代中,他们引入了不透明类型 ,可以使用您想要的功能。
在这种情况下,您可以这样称呼它:
func sendB() -> some BProtocol {
return B()
}
在此功能
func sendB_<T: BProtocol>() -> T{
return B() as! T
}
您不能将B
作为T
返回,因为使用该函数的人定义了T
是什么,而不是您,并且T
可以是符合Protocol
任何类型。例如,我可以这样做:
class C: BProtocol
{
typealias B = Float
}
let c: C = Main().sendB_()
通过这样做,我将T
设置为C
并且sendB_()
的强制类型转换将失败。
不幸的是,具有关联类型的协议本身不能被视为具体类型,因此您使用AProtocol
采取的方法将行不通。
如我所见,您有两个选择。 将函数返回类型更改为B
毕竟,您总是会返回B
func sendB_() -> B {
return B()
}
如果要使其通用,请尝试
protocol BProtocol
{
associatedtype B
init() // Needed to be able to do T() in generic function
}
func sendB_<T: BProtocol>() -> T{
return T()
}
您需要将初始化程序添加到协议中,以确保类型T
的实例始终存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.