使用JSONDecoder方法填充模型对象。由于需要在表视图上传递它,因此我需要在UI端初始化类型为KBArticle的局部变量。有没有没有可选的方法或直接访问内部数组的,初始化KBArticle对象的可能方法?
var kbArticle = KBArticle()
呼叫中缺少参数'from'的参数。插入'from:'
/// UI Side
var kbArticle = KBArticle()
override func viewDidLoad() {
super.viewDidLoad()
/// Web services call method
SDKCore.getInstance.getKbService().fetchKbArticles(with: topicID) { (result) in
switch result {
case .success(let kbArticle):
self.kbArticle = kbArticle
DispatchQueue.main.async {
self.tableView.reloadData()
}
case .failed(let e):
print("Error=\(e)")
}
}
}
// Model Class in SDK
public struct KBArticle: Codable {
public let id: Int
public let topic: String
public let articleCount: Int
public let articles: [Article]
}
public struct Article: Codable {
public let id: Int
public let subject: String
}
/// Method in SDK
public func fetchKbArticles(with topicId: Int, completionHandler: @escaping (ResultModel<KBArticle, Error>) -> Void) {
let request = GetKBArticles(topicId: topicId)
Networking.shared.performRequest(request) { (response) in
switch response {
case .success(let response):
do {
let decoder = JSONDecoder()
let result = try decoder.decode(KBArticle.self, from: response.data!)
completionHandler(.success(result))
} catch let error {
completionHandler(.failed(error))
}
case .failed(let error):
completionHandler(.failed(error))
}
}
}
我必须在
articles
结构中使用此kbArticle
来提供我的tableview数据源。无需使用nil值进行主初始化就可以初始化kbArticle
对象吗??? 最佳答案
如果需要不带可选参数的新对象,则可以为所有参数设置默认值
例如:
public struct KBArticle: Codable {
public var id: Int = 0
public var topic: String = ""
public var articleCount: Int = 0
public var articles: [Article]?
}
public struct Article: Codable {
public var id: Int = 0
public var subject: String = ""
}
使用:
let myObj = KBArticle()
请检查此Answer