外部范围内的访问变量

时间:2016-09-02 09:44:19

标签: swift

如果我在作用域中有一些变量(不是属性),并在内部作用域中重新定义它,是否有办法从内部作用域访问原始变量?这是一个例子:

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>这里有类似self的属性;有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

在您的代码中,if-block中的let cell = ...引入了一个新变量 cell从外部“隐藏”或“隐藏”cell变量 范围。据我所知,没有语言功能可供访问 具有相同名称的外部变量。

你可以通过立即评估的闭包获得类似的效果, 它在本地范围内创建和配置单元格,并传递 结果回到外部范围:

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