我有以下片段:
protocol MyProtocol: Identifiable where ID == UUID {
var id: UUID { get }
}
var test: [MyProtocol] = []
Run Code Online (Sandbox Code Playgroud)
协议“MyProtocol”只能用作通用约束,因为它具有 Self 或关联类型要求
为什么这不起作用?不应该where ID == UUID
消除错误所涉及的歧义吗?我在这里错过了什么吗?
我认为这个问题类似于这个问题:Usage of protocols as array types and function parameters in swift
但是,我会认为添加where ID == UUID
应该可以解决问题?为什么不是这样?
谢谢!
因此,在试验SwiftUI
和构建数据模型时出现了这个问题。我一直将类用于任何类型的数据模型,但似乎SwiftUI
想让您尽可能频繁地使用结构(我仍然不知道这在现实中是如何可能的,但这就是我尝试使用它的原因)。
在这种特殊情况下,我尝试让管理器包含所有符合MyProtocol
. 例如:
protocol MyProtocol: Identifiable where ID == UUID {
var id: UUID { get }
}
struct A: MyProtocol { // First data model
var id: UUID = UUID()
}
struct B: MyProtocol { // Second data model
var id: UUID = UUID()
}
class DataManager: ObservableObject {
var myData: [MyProtocol]
}
...
Run Code Online (Sandbox Code Playgroud)
我实际上不必声明Identifiable
,MyProtocol
但我认为它会更好更干净。
因为这不是 Swift 的当前功能。一旦有关联类型,总会有关联类型。它不会因为你限制它而消失。一旦它有一个关联的类型,它就不是具体的。
没有办法以这种方式“继承”协议。你的意思是:
protocol MyProtocol {
var id: UUID { get }
}
Run Code Online (Sandbox Code Playgroud)
然后您可以将 Identifiable 附加到需要它的结构:
struct X: MyProtocol, Identifiable {
var id: UUID
}
Run Code Online (Sandbox Code Playgroud)
(注意没有 where
条款。)
今天没有 Swift 特性允许你说“符合 X 的类型隐式符合 Y”。今天也没有 Swift 功能允许“符合 Identifiable with ID==UUID”的数组。(这称为广义存在主义,目前尚不可用。)
很可能你应该回到你的调用代码并探索你为什么需要它。如果您发布了迭代test
并特别需要Identifiable
一致性的代码,那么我们可能能够帮助您找到不需要的设计。
归档时间: |
|
查看次数: |
100 次 |
最近记录: |