Shadow Of Shadow Of - 3 months ago 15
Swift Question

Access variable in outer scope

If I have some variable (not property) in scope, and redefine it in inner scope, is there is way to access to original variable from inner scope? Here is example:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("awesomeCell", forIndexPath: indexPath) as! AwesomeTableViewCell
cell.delegate = self
<outscope>.cell = cell
} else {
cell = UITableViewCell()
}
return cell
}


<outscope>
here something like
self
for properties; is there is any way to do this?

Answer

In your code, let cell = ... in the if-block introduces a new variable cell which "hides" or "shadows" the cell variable from the outer scope. There is – as far as I know – no language feature to access the outer variable with the same name.

You can achieve a similar effect with an immediately evaluated closure, which creates and configures the cell in a local scope, and passes the result back to the outer scope:

    let cell: UITableViewCell
    if indexPath.section == 0 {
        cell = {
            let cell = tableView.dequeueReusableCellWithIdentifier("awesomeCell", forIndexPath: indexPath) as! AwesomeTableViewCell
            cell.delegate = self
            return cell
        }()
    } else {
        // ...
    }