所以我有两个模型,一个名为AppCategory和App。我在AppCategory类中创建了一个函数,它创建了一个API调用,让我成功地回到了所有类别,在这些类别中,有一系列的应用程序字典,我以字典的形式返回,但是我是不确定如何将其设置为App对象。
这是我的AppCategory类:
import UIKit
class AppCategory {
var name: String?
var apps = [App]()
var type: String?
init(dictionary: [String: Any]) {
name = dictionary["name"] as? String
apps = dictionary["apps"] as! [App]
type = dictionary["type"] as? String
}
static func fetchFeaturedApps(completion: @escaping ([AppCategory]) -> Void) {
guard let url = URL(string: "https://api.letsbuildthatapp.com/appstore/featured") else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
return
}
guard let data = data else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
var appCategories = [AppCategory]()
for dict in json["categories"] as! [[String: Any]] {
let appCategory = AppCategory(dictionary: dict)
appCategories.append(appCategory)
if dict.index(forKey: "apps") != nil {
}
}
print(appCategories)
DispatchQueue.main.async {
completion(appCategories)
}
} catch {
print("Error in JSON Serialization")
}
}.resume()
}
}
以下是App模型类:
import Foundation
class App {
var id: Int?
var name: String?
var category: String?
var price: Double?
var imageName: String?
init(dictionary: [String: Any]) {
id = dictionary["Id"] as? Int
name = dictionary["Name"] as? String
category = dictionary["Category"] as? String
price = dictionary["Price"] as? Double
imageName = dictionary["ImageName"] as? String
}
}
我已经完成了研究,我可以制作NSObject类型的这些类并使用setValue(forKey :),但我并不是真的想这样做。通过说dict.index(forKey:" apps")!= nil,我已经知道在AppCategory类中突出显示的是什么......不知道是否...我正走在正确的轨道上,但也许有人可以帮我解决这个问题。