如何使用swift 4.2在nameDidload和Search选项中按名称字段执行可编码值?

问题描述 投票:1回答:1

我正在使用codable并试图从data回应中获取JSON。在这里,我无法使用viewDidload将特定值打印到swift 4.2并且我正在使用搜索,但我想指定名称为filteredDatavalues

我的代码

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
}
ios swift uisearchbar
1个回答
0
投票

您需要创建一个Root类型的新变量,例如var root : Root,并且在viewDidLoad上,如果它来自API或本地JSON文件,则使请求(解码)依赖。然后解码的结果将保存在根变量中

root = result

然后你可以访问root.cost

我还建议你看看这个video它会帮助你理解如何使用decodable

© www.soinside.com 2019 - 2024. All rights reserved.