0 Replies - 451 Views - Last Post: 17 September 2017 - 01:59 PM

#1 jlis  Icon User is offline

  • D.I.C Head

Reputation: 13
  • View blog
  • Posts: 222
  • Joined: 02-February 15

Variable captured by a closure before being initialized - Swift/XCode

Posted 17 September 2017 - 01:59 PM

Hello,

I'm getting the error in the question and unsure how to fix it. I've not really worked much with closures before. I basically want to have a variable returned by this function but it's value to be set inside a closure. With a closure being self contained I'm unsure how to get around the error :/

        let task = URLSession.shared.dataTask(with: request) { data,response,error in guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
            }
            do {
                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                } else {
                    menu = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] ?? []
                    var dictionary = [Int:Any]()
                    for (index,item) in menu.enumerated() {
                        let uniqueID = index
                        dictionary[uniqueID] = item
                    }
                }
            } catch let error as NSError {
                print(error)
            }
            
        }
        task.resume()
        return menu
    }



Is This A Good Question/Topic? 0
  • +

Page 1 of 1