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

时间:2018-03-28 04:46:11

标签: swift struct

我不确定如何在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 ?? ""
    }
}

4 个答案:

答案 0 :(得分:0)

在struct

中初始化一个数组
struct MyData {

  var dataArray:[Any] = []
  var latitude:  Float
  var longitude: Float
}

答案 1 :(得分:0)

在您的数据中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 ?? ""
    }
}

答案 2 :(得分:0)

您必须将字典解包为字典数组,然后使用地图或平面图循环显示字典,其中使用值$0作为值

guard let serviceList = (json["service_list"] as? [[String: Any]])?.flatmap({ServiceList(withDictionary: $0)})

答案 3 :(得分:0)

采用以下方法,这样更简单

使用Codable

创建您的结构
struct Platform: Codable {
    let service_list: [ServiceList]
    let status: String

    enum CodingKeys: String, CodingKey {
        case service_list, status
    }
}


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

    enum CodingKeys: String, CodingKey {
        case title, description, image
    }
}

您的json数据对象

let 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"
    }
    ]
}
""".data(using: .utf8)!

使用JSONDecoder将json对象映射到结构

let decoder = JSONDecoder()
let platform = try! decoder.decode(Platform.self, from: json)
if platform.status == "pass"{
    for service in platform.service_list{
        print(service.title)
    }
}