0

The model object is populated using JSONDecoder method. Since it is needed to pass it on tableview i need to initialise a local variable of type KBArticle on UI side. Is there any possible method of initialising an object of the KBArticle without optionals or accessing the inner array directly ?

var kbArticle = KBArticle()

Missing argument for parameter 'from' in call. Insert '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))
        }
    }
}

I have to use this articles inside kbArticle struct to provide my tableview datasource. Is is possible to initialise kbArticle object without a primary initialisation using nil values???

Community
  • 1
  • 1
Vaisakh KP
  • 467
  • 1
  • 6
  • 25

1 Answers1

0

If you need new object without optional , you can set a default value for all params

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 = ""
}

Use: let myObj = KBArticle()

Please check this Answer

a.masri
  • 2,439
  • 1
  • 14
  • 32