gpt4 book ai didi

ios - 如何使用 swift 4.2 按名称字段在 viewDidload 和搜索选项中执行可编码值?

转载 作者:行者123 更新时间:2023-11-28 07:30:52 25 4
gpt4 key购买 nike

我正在使用 codable 并尝试从 JSON 响应中获取 data。在这里,我无法使用 swift 4.2 将特定值打印到 viewDidload 中,我正在使用搜索,但我想为 filteredData 分配名称

我的代码

struct Root: Codable {
let status: Int
let message: String
let country: [Country]
let cost: Double
let data: [Datum]
}

struct Country: Codable {
let id: Int
let master: String
let type, active: Int
}

struct Datum: Codable {
let id, userID, country, card: Int
let category: Int
let title, description: String
let cost: Double
let attachment, createDate, deviceID, appType: String
let location: String
let user: User
let appTransCard: AppTransCard
let appTransMaster: AppTransMaster

enum CodingKeys: String, CodingKey {
case id
case userID = "user_id"
case country, card, category, title, description, cost, attachment
case createDate = "create_date"
case deviceID = "device_id"
case appType = "app_type"
case location, user
case appTransCard = "app_trans_card"
case appTransMaster = "app_trans_master"
}
}

struct AppTransCard: Codable {
let card: String
}

struct AppTransMaster: Codable {
let master: String
}

struct User: Codable {
let firstname, lastname: String
}

我需要从 Root.cost. 获取 viewdidload 中的值。

override func viewDidLoad() {
super.viewDidLoad()

// here I need to print Root.cost value
}

最佳答案

您需要创建一个类型为 Root 的新变量例如 var root : Root并在 viewDidLoad 上发出请求(解码)取决于它是来自 API 还是本地 JSON 文件。然后解码的结果将保存在根变量中

根=结果

然后你可以访问root.cost

我也推荐你看这个video它将帮助您了解如何使用 decodable

关于ios - 如何使用 swift 4.2 按名称字段在 viewDidload 和搜索选项中执行可编码值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54745836/

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