在JSON模型中使用枚举类型访问struct属性的语法

时间:2018-12-02 09:37:22

标签: json swift syntax model

我正在尝试访问一些JSON数据中包含的url字符串。

该字符串包含在“ urls”数组中,类型为“ detail”,如下所示。

JSON DATA

我使用quicktype来构建我的模型,如下所示:

struct Response: Codable {
    let data: DataClass
}

struct DataClass: Codable {
    let results: [Result]
}

struct Result: Codable {
    let name: String
    let description: String
    let thumbnail: Thumbnail
    let urls: [URLElement]


}

    struct Thumbnail: Codable {
        let path: String
        let thumbnailExtension: Extension

        enum CodingKeys: String, CodingKey {
            case path
            case thumbnailExtension = "extension"
        }
    }

    enum Extension: String, Codable {
    case jpg = "jpg"
}

struct URLElement: Codable {
    let type: URLType
    let url: String
    }

    enum URLType: String, Codable {
        case comiclink = "comiclink"
        case detail = "detail"
        case wiki = "wiki"
    }

我试图通过这样声明来访问它...

var urlelement: URLElement!


    override func viewDidLoad() {
        super.viewDidLoad()
        let detailurl = urlelement.url
        print(detailurl)

...但是它总是返回一个空字符串。任何建议都将受到欢迎。谢谢!

1 个答案:

答案 0 :(得分:0)

首先下载JSON,然后下载用户JSONDecoder

让url = URL(字符串:“您的url”)!

URLSession.shared.dataTask(with:url){(数据,响应,错误)在

if let error = error {
    print("error \(error.localizedDescription)")
    return
}

guard let data = data else { return }

do {
    let response = try JSONDecoder().decode(Response.self, from: data)
    // use this

    response?.data.results.forEach({ (rsl) in
        rsl.urls.forEach({ (element) in
            print(element.type, element.url)
        })
    })

    // or this one

    for rsl in response!.data.results {
        for element in rsl.urls {
            print(element.type, element.url)
        }
    }
} catch let error {
    print("error while decoding the json \(error.localizedDescription)")

}

}.resume()