我正在使用codable
并试图从data
回应中获取JSON
。在这里,我无法使用viewDidload
将特定值打印到swift 4.2
并且我正在使用搜索,但我想指定名称为filteredData
的values
。
我的代码
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
}
我需要从viewdidload
获得Root.cost.
内的值
override func viewDidLoad() {
super.viewDidLoad()
// here I need to print Root.cost value
}
您需要创建一个Root
类型的新变量,例如var root : Root
,并且在viewDidLoad上,如果它来自API或本地JSON文件,则使请求(解码)依赖。然后解码的结果将保存在根变量中
root = result
然后你可以访问root.cost
我还建议你看看这个video它会帮助你理解如何使用decodable