[英]Two functions with one variable in Swift
我在視圖控制器中有兩個功能。 第一個函數解析JSON並創建一個數組。 另一個生成一個包含數組數據的表。 問題在於,似乎第一個函數無法將其數組數據發送給第二個函數。
這是代碼:-
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
}
}
這段代碼在tableView
函數中有一個錯誤:
使用未解決的標識符“ chartContent”
我試圖在第一個函數的外部聲明變量,該函數secondViewController
在類secondViewController
下,但是UITableViewDataSource
上存在另一個錯誤。
有什么解決辦法嗎?
Charttitle是在任何過程之外定義的,因此可在任何地方使用。 Chartcontent是在塊中定義的,因此僅在塊中可用
這是因為chartContent是一個局部變量,僅可用於解析func,並且其作用域直到該func塊為止。 您必須以與chartTitle相同的方式創建此變量,以使其在整個類中都可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.