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

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()'
可能吗?

最佳答案

在此功能

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类型的实例。

09-10 03:57
查看更多