【发布时间】:2021-04-18 16:17:22
【问题描述】:
我需要在视图中显示符合通用协议的不同结构的数组。
正如SwiftUI - View showing Elements conforming to a Protocol and ForEach over them 中所建议的那样,我尝试过这样 - 效果很好!
现在我需要检查数组的元素是否相等。
让协议符合Equatable 不会编译 -
它得到错误:Protocol 'Suggest' can only be used as a generic constraint because it has Self or associated type requirements。
//protocol Suggest :Equatable {
protocol Suggest {
var desc: String { get }
}
struct Person : Suggest {
var surname : String
var name: String
var id: String { return name }
var desc: String { return name }
}
struct Book : Suggest {
var titel : String
var abstact : String
var id: String { return titel }
var desc: String { return titel }
}
let books = [ Book(titel: "book 1", abstact: "abstract1"),
Book(titel: "book 2", abstact: "abstract2")
]
let persons = [ Person(surname: "John", name: "Doe"),
Person(surname: "Susan", name: "Smith"),
Person(surname: "Frank", name: "Miller")
]
struct ContentView: View {
var body: some View {
VStack {
SuggestList(list: books)
SuggestList(list: persons)
}
}
}
struct SuggestList: View {
var list : [Suggest]
// this line does not compile, if Suggest conforms to Equitable
// "Protocol 'Suggest' can only be used as a generic constraint because it has Self or associated type requirements"
var body: some View {
List(list.indices, id: \.self) { index in
Text(list[index].desc)
// .onTapGesture {
// if list.contains(list[index]){print ("hello")}
// }
}
}
}
【问题讨论】:
标签: swift swiftui swift-protocols