gpt4 book ai didi

Swift - 如何在结构中初始化数组?

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

我不确定如何初始化 Struct 中的数组。 我无法从数组中获取数据,同时我设法从对象(platform.status)获取结果。

我初始化错了吗?有什么想法吗?

这是网络请求:

func fetchServicePlatform(token: String, _key: String) {
let selectedUrl = URL(string: "\(mainUrl)/get_service")
let parameters: [String: String] = ["_key": _key]
var serviceList = [ServiceList]()

URLSession.shared.dataTask(with: setupURLRequest(selectedURL: selectedUrl!, parameters: parameters, token: token, email: "test@gmail.com")) { (data, response, error) in
if let err = error {
print("Failed to fetch API: \(err.localizedDescription)")
}

guard let data = data else { return }

do {
guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else { return }
let platform = Platform(json: json)

if platform.status == "success" {

self.serviceList = platform.service_list

DispatchQueue.main.async {
self.collectionView.reloadData()
}
}

} catch let jsonErr {
print("Failed to fetch service platform: ", jsonErr.localizedDescription)
}
}.resume()
}

这是 JSON:

{
"status": "pass",
"service_list": [
{
"title": "Plumber",
"description": "Plumber",
"image": "https://s3-ap-southeast-1.heroku.com.png"
},
{
"title": "Cleaner",
"description": "Cleaner",
"image": "https://s3-ap-southeast-1.heroku.com.png"
}
]
}

这是结构:

struct Platform {
let service_list: [ServiceList]
let status: String

init(json: [String: Any]) {
service_list = [ServiceList(json: json["service_list"] as? [String: Any] ?? [:])]
status = json["status"] as? String ?? ""
}
}


struct ServiceList {
let title: String
let description: String
let image: String

init(json: [String: Any]) {
title = json["title"] as? String ?? ""
description = json["description"] as? String ?? ""
image = json["image"] as? String ?? ""
}
}

最佳答案

在您的数据中json["service_list"]是一个字典数组,

你可以尝试一下。

struct Platform {
var service_list: [ServiceList] = []
var status: String

init(json: [String: Any]) {
if let jsonArray = json["service_list"] as? [[String: Any]] {
for service in jsonArray {
service_list.append(ServiceList(json: service))
}
}
else{
service_list = []
}
status = json["status"] as? String ?? ""
}
}

关于Swift - 如何在结构中初始化数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49526275/

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