gpt4 book ai didi

ios - 返回具有关联类型的协议(protocol)

转载 作者:行者123 更新时间:2023-11-29 05:32:17 25 4
gpt4 key购买 nike

如何返回关联类型的协议(protocol)?

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(具有关联类型的协议(protocol))不完全类型。它们充当类型的占位符。所以你不能直接返回BProtocol

swift 5.1

我不是 100% 确定,但我认为在 swift (5.1) 的下一个迭代中,他们引入了不透明类型,它可以实现您想要的功能。

在这种情况下,您可以这样调用它:

func sendB() -> some BProtocol { 
return B()
}

关于ios - 返回具有关联类型的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57427864/

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