[英]Two functions with one variable in Swift
I have two functions in a view controller. 我在视图控制器中有两个功能。 The first function parses JSON and makes an array;
第一个函数解析JSON并创建一个数组。 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: 这段代码在
tableView
函数中有一个错误:
Use of unresolved identifier 'chartContent'
使用未解决的标识符“ 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
. 我试图在第一个函数的外部声明变量,该函数
secondViewController
在类secondViewController
下,但是UITableViewDataSource
上存在另一个错误。
Any solution for these? 有什么解决办法吗?
Charttitle is defined outside any procedure, so it's available everywhere. Charttitle是在任何过程之外定义的,因此可在任何地方使用。 Chartcontent is defined in a block, so it's usable just in it's block
Chartcontent是在块中定义的,因此仅在块中可用
Its because chartContent is a local variable just available to parseJson func only and its scope is till that func block. 这是因为chartContent是一个局部变量,仅可用于解析func,并且其作用域直到该func块为止。 You have to create this variable the same way you dis chartTitle to be available throughout the class.
您必须以与chartTitle相同的方式创建此变量,以使其在整个类中都可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.