gpt4 book ai didi

swift - 访问外部作用域中的变量

转载 作者:可可西里 更新时间:2023-11-01 01:31:12 25 4
gpt4 key购买 nike

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

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 的东西对于属性;有什么办法可以做到这一点?

最佳答案

在您的代码中,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 {
// ...
}

关于swift - 访问外部作用域中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39289329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com