我正在尝试使用属性get / set来访问结构体数组 每个TransactionRecord结构都有一个位置,并且每个位置都有一系列事务。每个交易的类型为TransactionRecord
这是我的代码:
struct TransactionRecord {
var transactionId: String
var transactionType: String
}
struct TransactionPackage{
var location: String
var transactions: [TransactionRecord]
}
var data = TransactionPackage(location: "", transactions: []) {
didSet {
if oldValue == nil || data == nil {
tableView.reloadData()
}
}
}
var transaction: TransactionPackage {
get {
var transactions = [TransactionRecord]()
if data.transactions.count > 1 {
for transaction in data.transactions.last ?? [TransactionRecord] {
transactions.append(transaction)
}
}
return TransactionPackage(location: data.location, transactions: transactions)
}
set {
data = [[newValue.location], newValue.transactions]
}
}
我遇到多个错误: 在线: 用于data.transactions.last中的交易[TransactionRecord] { 我得到错误: 无法将类型“ [TransactionRecord] .Type”的值转换为预期的参数类型“ TransactionRecord”
在线: 数据= [[[newValue.location],newValue.transactions] 我得到错误: 无法将类型“ [Any]”的值分配给类型“ TransactionPackage”
我可以寻求帮助吗?
答案 0 :(得分:0)
第一个错误表明您使用的是类型[TransactionRecord]
作为默认值,而不是该类型的实例,例如空数组[]
第二个错误表明您无法将[Any]
分配给值TransactionPackage
我想您想将data
映射到transaction
作为计算属性
var transaction: TransactionPackage {
get {
return TransactionPackage(location: data.location, transactions: data.transactions)
}
set {
data = TransactionPackage(location: newValue.location, transactions: newValue.transactions)
}
}
或更简单
var transaction: TransactionPackage {
get {
return data
}
set {
data = newValue
}
}
答案 1 :(得分:0)
此处为正确的代码。
this
更正
struct TransactionRecord { var transactionId: String var transactionType: String } struct TransactionPackage{ var location: String var transactions = [TransactionRecord]() } var data = TransactionPackage(location: "", transactions: []) { didSet { //tableView.reloadData() } } var transaction: TransactionPackage { get { var trans = [TransactionRecord]() if data.transactions.count > 1 { //Corrections 1,2 for transaction in data.transactions ?? [] { trans.append(transaction) } } return TransactionPackage(location: data.location, transactions: trans) } set { //Corrections 3 data = TransactionPackage(location: newValue.location, transactions: newValue.transactions) } }