SwiftyJSON深层复制

时间:2018-04-20 17:33:51

标签: json swift swifty-json


我正在做一个ServerTransport课程,而且我遇到了一些问题...
长话短说,我希望ServerTransport对象能够获得和/或在self.link发布数据。 类成员self.dataOut应该包含来自服务器的任何内容。 方法receive()应创建请求并将所有内容放入dataOut。

我使用SwiftyJSON并了解了merged(with:)方法。
我曾希望创建一个名为json的临时常量,并将其深层复制到self.dataOut中。为了更加确定,我将json与自己合并。 没有这样的运气。只要json常量超出范围,self.dataOut成员就会再次成为JSON()。

我做错了吗?我打算做什么甚至可能? 以下是我的代码。

<小时/> 在此先感谢。

class ServerTransport {
var dataIn: Data?
var dataOut : JSON
var link: String
var responseType : String

init(_ link : String, _ responseType : String = "application/json", _ dataIn : Data? = nil) {
    self.dataIn = dataIn
    self.link = link
    self.responseType = responseType
    self.dataOut = JSON()
}

func receive() {
    var request = URLRequest(url: URL(string: self.link)!)
    request.httpMethod = "GET"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let error = error {
            print("Error : \(error)")
            return
        }
        guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
          return
        }

        if let mimeType = response.mimeType, mimeType == self.responseType, let data = data{
            guard let json = try? JSON(data : data) else {
                return
            }
            do {
               self.dataOut = try json.merged(with: json)
            }catch {
                print("exception")
                // nothing let's just hope that we won't ever reach this point
            }
        }
        print(self.dataOut) // Correct data from server
    }
    task.resume()
    print(self.dataOut) // Empty JSON ... Is it because the json variable is out of scope ?
    // Wasn't merge supposed to give a deep copy of json?
}

0 个答案:

没有答案