2

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?

Yury
  • 6,044
  • 3
  • 19
  • 41
  • 3
    No. Use a different variable name or a "immediately evaluated closure". – But why would you want to create and return an unconfigured cell in the else case? Compare http://stackoverflow.com/questions/30189505/missing-return-uitableviewcell for better options to avoid the "missing return" error message. – Martin R Sep 02 '16 at 09:50
  • @MartinR Thank you! Immediately evaluated closure looks nice idea for that. For else case I used shortest template as I imagine just for make valid code. – Yury Sep 02 '16 at 09:58
  • @MartinR I looked your link, and yes, `@noreturn` function looks more elegant template – Yury Sep 02 '16 at 10:03

1 Answers1

2

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 {
        // ...
    }
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382