没有可选参数的初始化模型对象

时间:2019-01-01 12:50:32

标签: swift model initialization jsondecoder

使用JSONDecoder方法填充模型对象。由于需要在表视图上传递它,因此我需要在UI端初始化一个类型为KBArticle的局部变量。是否有任何可能的方法可以初始化KBArticle的对象而无需使用可选参数或直接访问内部数组?

  

var kbArticle = KBArticle()

     

在调用中缺少参数'from'的参数。插入'from:<#Decoder#>'

/// 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对象吗?

1 个答案:

答案 0 :(得分:0)

如果需要不带可选参数的新对象,则可以为所有参数设置默认值

ex:

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