Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Use of unresolved identifier" with Swift

I am rewriting one of my apps in Swift, that displays live weather data for South Kohala. Love Swift so far!

I'm having one small problem that is holding things up. I have a tab bar based app, iPad only.

One of my tabs is a UIViewController with a TableView added to it in the storyboard to display NOAA forecasts. I have a data class Data that retrieves the list from our server and creates a constant List in viewDidLoad. It is an array of arrays with four strings in each subarray.

I have verified that it's there, as I can create a constant: List[0] and println all the strings.

However, when I go to use it to populate the table view, I get a "Use of unresolved identifier" error. If instead, I try setting the cell Title to "Test" that works OK.

This seems like a scope issue, but as the constant is created within the class, I just don't understand why it's not visible in the tableView function. I've looked at dozens of posts on this, but nothing I have found seems to help. Here is the code:

import UIKit

class ForecastsViewController: UIViewController,   UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var forecastsTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let instanceofData: Data = Data()
        let list = instanceofData.forecastsList() as NSArray
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
      var forecastList:NSArray = list[indexPath.row] //selects one of the arrays from List
      cell.textLabel?.text = forecastList[0] as string
           return cell
    }
like image 854
Snorkeler Avatar asked Oct 13 '14 15:10

Snorkeler


1 Answers

It is because List is purely local to the inside of viewDidLoad; where you've declared it, other methods cannot see it.

Contrast, for example, forecastsTable, which is declared outside any method, which means that any method can see it.

This behavior is called "scope" and is crucial to any programming language. Variables declared inside a method are neither visible outside it nor do they persist when that method has finished running. Thus, in your example, not only is List not visible when cellForRowAtIndex runs, it doesn't even exist when cellForRowAtIndex runs - it has been destroyed long before.

like image 84
matt Avatar answered Nov 05 '22 10:11

matt