简体   繁体   中英

Two functions with one variable in Swift

I have two functions in a view controller. The first function parses JSON and makes an array; another generates a table with the array data. The problem is that it seems that the first function cannot send its array data to the second function.

Here is the code:-

class secondViewController: UIViewController, UITableViewDataSource {
    let chartTitle:[String] = ["Name",......]

    func parseJSON(){
        let url = NSURL(string: "http://00000.us-west-2.elasticbeanstalk.com/index.php?000000")
        let request = NSURLRequest(URL: url!)
        do {
            let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
                var name = json["Name"]
                var chartContent:[String] = ["\(name)",.....]   //Contents of current chart contents
            } catch{
                //Handle Exception
            }
        } catch{
            //Handle Exception
        }
    }

    override func viewDidLoad() {
        parseJSON()
        ...
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {   //currnet table information.
        let cell = UITableViewCell()
        cell.textLabel?.text = chartTitle[indexPath.row] + "\t\t\t\t\t here comes info" + chartContent[indexPath.row]
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return chartTitle.count
    }
}

This code has an error at the tableView function:

Use of unresolved identifier 'chartContent'

I tried to declare the variables outside the first function which is right under the class secondViewController but there was another error on UITableViewDataSource .

Any solution for these?

Charttitle is defined outside any procedure, so it's available everywhere. Chartcontent is defined in a block, so it's usable just in it's block

Its because chartContent is a local variable just available to parseJson func only and its scope is till that func block. You have to create this variable the same way you dis chartTitle to be available throughout the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM