swift - 是否可以在协议(protocol)内声明具有关联类型的协议(protocol)?

标签 swift

我想在协议(protocol)内声明一个具有关联类型的协议(protocol)。

我知道将其声明为类而不是协议(protocol)可以解决问题。

但我想在协议(protocol)内使用它。

有没有办法使用泛型或类型别名等协议(protocol)来使用协议(protocol)中的关联类型?

protocol A {
    associatedtype T
}

protocol B {
    var a: A { get } // error. protocol 'A' can only be used as a generic constraint because it has Self or associated type requirements
                     // But I want set a.T = Int
}

最佳答案

如果您确实要将 A.T 设置为 Int,您可以在 B: 内的关联类型 where 子句中指定该值

>
protocol A {
    associatedtype T
}

protocol B {
    associatedtype U: A where U.T == Int 
    var a: U { get }
}

或者,您不想将 B 锁定为仅一种特定的 A.T 类型,您可以引入另一种 linkedtype,它链接回A:

protocol A {
    associatedtype T
}

protocol B {
    associatedtype T
    associatedtype U: A where U.T == T 
    var a: U { get }
}

参见Associated Types with a Generic Where Clause Swift 编程语言。

关于swift - 是否可以在协议(protocol)内声明具有关联类型的协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70021694/

相关文章:

json - 使用 swiftjson 遍历对象

arrays - 调用中缺少参数标签 'combine:'

ios - 是否可以将动态变量用于类成员变量

swift - 从 CoreData 获取并转换

swift - 删除 swift 字符串的最后一个标点符号

ios - 如何显示刚刚选中的照片库中的图像?

ios - 按 JSON 数组对 TableView 进行分组

swift - 如何使用字符串值作为对象名称?

objective-c - Xcode 6 Swift代码完成不起作用

ios - UIButton 闪烁正常工作,但按钮操作不工作