'How to deep copy data from completionHandler clousure to ViewController class in Swift?
I've tried to DeepCopy data with NSCopying protocol and with JSON decoder/encoder, but everytime I stumble upon somewhere and can't get it fixxed.
How can I copy exactly the same all of the contents from result to class variable postData? I'd like to add it to tableview programaticly but I just can't get it to work.
Here is ViewController class code:
class ViewController: UIViewController {
var postData:[Post] = []
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
DataLoader.shared.fetchPostData(completionHandler: {
result in
//it prints result here
for x in result{
print(x.id!)
}
self.postData = result
})
//I'd like to print it here
for x in self.postData{
print(x.id!)
}
}
Here is Post class code:
import Foundation
struct Post: Decodable{
var userId: Int!
var id: Int!
var title: String!
var body: String!
}
and here is DataLoader class code:
import Foundation
class DataLoader: Codable {
//var classData:[Post] = []
static let shared = DataLoader()
func fetchPostData(completionHandler: @escaping ([Post]) -> Void){
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
URLSession.shared.dataTask(with: url) {
(data, response, error) in
guard let data = data else { return }
do {
let postsData = try JSONDecoder().decode([Post].self, from: data)
//self.classData = postsData
completionHandler(postsData)
}
catch {
let error = error
print(error.localizedDescription)
//completionHandler(nil)
}
}.resume()
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|