从 swift 中的 do-catch 语句中获取变量

Getting Variable out of do-catch statement in swift

我想知道如何使用 do-catch 语句中的变量。我正在从网络上解析一些 JSON 并用它填充一个对象,但随后我需要那个对象在外面来填充一个 UITableView。我获取网络信息的功能:

func post(dburl: String, info: String, completionHandler: (NSString?, NSError?) -> ()) -> NSURLSessionTask {

let myUrl = NSURL(string: dburl)!;
let request = NSMutableURLRequest(URL:myUrl);
request.HTTPMethod = "POST";
let postString = info //finalPlaceId = info
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
    { data, response, error in dispatch_async(dispatch_get_main_queue()) {
        guard data != nil else {
            completionHandler(nil, error)
            return
        }
        completionHandler(NSString(data: data!, encoding: NSUTF8StringEncoding), nil)

        }
}
task.resume()
return task
}

所以,我调用函数并在内部执行 do-catch:

post(dburl, info: finalPlaceId) { responseString , error in
                        guard responseString != nil else {
                            print(error)
                            return

                        }

                        do { if  let dataDB = responseString!.dataUsingEncoding(NSUTF8StringEncoding) {

                            var error: NSError?
                            let jsonDB = try NSJSONSerialization.JSONObjectWithData(dataDB, options:[])

                            //print(jsonDB)

                            if let infoArray = jsonResults["results"] as? [NSDictionary] {

                                if let infoArrayDB = jsonDB as? [NSDictionary] {

                                    for item in infoArray {
                                            for item2 in infoArrayDB {

                                                self.JSON_Info.append(JSONInfo(json: item))
                                                self.JSON_Info.append(JSONInfo(json: item2))

                                    }
                                    }
                                    print(infoArrayDB)

                                }


                            }

                        }
                        } catch {                print("Fetch Failed:\(error as NSError).localizedDescription)")
}



                       // print(responseString!)

                    }

现在可以从这个函数中使用 JSON_Info 吗?如果没有,即使采用其他变量就足够了,这样我就可以在函数外执行 for 循环。理想情况下,我想在函数之外使用 infoArray 和 infoArrayDB。感谢您的帮助。

首先创建对象声明 class :

  var infoArray : [NSDictionary]?
  var infoArrayDB : [NSDictionary]?
  post(dburl, info: finalPlaceId) { responseString , error in
                    guard responseString != nil else {
                        print(error)
                        return

                    }

                    do { if  let dataDB = responseString!.dataUsingEncoding(NSUTF8StringEncoding) {

                        var error: NSError?
                        let jsonDB = try NSJSONSerialization.JSONObjectWithData(dataDB, options:[])

                        //print(jsonDB)

                        if let infoArray = jsonResults["results"] as? [NSDictionary] {
                        self.infoArray = infoArray
                            if let infoArrayDB = jsonDB as? [NSDictionary] {
                        self.infoArrayDB = infoArray
                                for item in infoArray {
                                        for item2 in infoArrayDB {

                                            self.JSON_Info.append(JSONInfo(json: item))
                                            self.JSON_Info.append(JSONInfo(json: item2))

                                }
                                }
                                print(infoArrayDB)

                            }


                        }

                    }
                    } catch {                print("Fetch Failed:\(error as NSError).localizedDescription)")
  }



                   // print(responseString!)

                }

现在您可以在任何地方查看用户

    if let infoArray = self.infoArray{
      /// Do whatever you want

}

你在 do/catch 之前声明它们,然后使用它们,前提是你将它们声明为可选的,并且你也在 catch 中给它们赋值:

let infoArray : [NSDictionary]?
let infoArrayDB : [NSDictionary]?

do {
    // your code from above
} catch {
    infoArray = nil
    infoArrayDB = nil
}

let 允许您稍后进行赋值,因此我们可以使用它而不将两者保持为常量(Swift 方式)。

请注意,如果您想使用它们,您需要打开它们,这有点重复您在 do/catch.

内部的工作