我有一堂课,看起来像这样:
public class TransactionResults: Identifiable {
public typealias CustomClassValue = Transaction
public typealias CustomClassIndex = Array<CustomClassValue>.Index
public let id = UUID()
private let transactions = sampleTransactions
}
extension TransactionResults: RandomAccessCollection {
public var startIndex: CustomClassIndex { return transactions.startIndex }
public var endIndex: CustomClassIndex { return transactions.endIndex }
public subscript(index: CustomClassIndex) -> CustomClassValue? {
get { if index >= 0 && index < transactions.count {
return transactions[index]
} else {
return nil
}
}
}
}
当我尝试将其与ForEach一起使用时,出现错误:Cannot convert value of type 'TransactionResults' to expected argument type 'Range<Int>'
struct TransactionListView: View {
@State private var transactions = TransactionResults()
var body: some View {
NavigationView {
List() {
ForEach(transactions) { transaction in
EmptyView()
}
}
}
}
}
要使其正常运行,我需要在TransactionResults类中进行哪些更改?
答案 0 :(得分:1)
如果您正确声明了Transaction
类(顺便说一下,它可能会与SwiftUI Transaction
类型冲突,所以我建议重命名您的类型),那么就需要全部(至少与Xcode 11.4)将使用其他ForEach
构造函数:
ForEach(transactions, id: \.self) { transaction in
EmptyView()
}
更新:这是一个用于测试代码快照的事务类(正如我提到的,我将其重命名以避免与内置类型冲突)
class ATransaction: Equatable, Identifiable, Hashable {
static func == (lhs: ATransaction, rhs: ATransaction) -> Bool {
lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
let id = UUID()
}