gpt4 book ai didi

swift - 如何访问结构中的字典

转载 作者:行者123 更新时间:2023-11-28 09:40:19 25 4
gpt4 key购买 nike

我有一个结构,结构内部有一个字典,我想访问结构内部字典的内容。

这是我的结构:

struct TransactionsObject: Codable {
let UserInitiatedTransactions: [UserEdTransaction]?
let UserReceivedTransactions: [UserEdTransaction]?

enum CodingKeys: String, CodingKey {
case UserInitiatedTransactions = "UserInitiatedTransactions"
case UserReceivedTransactions = "UserReceivedTransactions"
}
}

struct UserEdTransaction: Codable {
let transactionCode: Int?
let transactionDate: String?
let transactionType: String?
let transactionTime: String?
let transactionAmount: String?
let transactionTo: String?
let transactionFrom: String?

enum CodingKeys: String, CodingKey {
case transactionCode = "transactionCode"
case transactionDate = "transactionDate"
case transactionType = "transactionType"
case transactionTime = "transactionTime"
case transactionAmount = "transactionAmount"
case transactionTo = "transactionTo"
case transactionFrom = "transactionFrom"
}
}

我想访问这个transactionCode。我已经对 TransactionsObject.UserInitiatedTransactions.transactionCode 进行了尝试,但出现以下错误:

Value of type '[UserEdTransaction]?' has no member 'transactionCode'

最佳答案

首先的问题应该是如何访问结构中的数组 😉

其次,仅当结构成员和键与例如lowerCamelCase 变量名称不匹配时才使用CodingKeys

第三点仅将结构的成员声明为可选的,其键等价物可能会丢失

struct TransactionsObject: Codable {
let userInitiatedTransactions: [UserEdTransaction]
let userReceivedTransactions: [UserEdTransaction]

enum CodingKeys: String, CodingKey {
case userInitiatedTransactions = "UserInitiatedTransactions"
case userReceivedTransactions = "UserReceivedTransactions"
}
}

struct UserEdTransaction: Codable { // no CodingKeys !!
let transactionCode: Int
let transactionDate: String
let transactionType: String
let transactionTime: String
let transactionAmount: String
let transactionTo: String
let transactionFrom: String
}

错误发生是因为userInitiatedTransactions 是一个数组。您需要索引订阅

print(transactionsObject.userInitiatedTransactions[0]) // can crash if the array is empty

或重复循环

for transaction in transactionsObject.userInitiatedTransactions {
print(transaction.transactionCode)
}

关于swift - 如何访问结构中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50193712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com