1

我有一个看起来像这样的类:

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 类中更改什么才能正常工作?

4

1 回答 1

1

如果您正确声明了您的Transaction类(顺便说一句,它可能与 SwiftUITransaction类型冲突,所以我建议重命名您的类型),那么(至少在 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()
}
于 2020-05-27T13:29:41.077 回答