【问题标题】:Error: Variable with getter/setter cannot have an initial value错误:带有 getter/setter 的变量不能有初始值
【发布时间】:2016-03-15 13:12:07
【问题描述】:

如何解决这个错误?

带有getter/setter的变量不能有初始值

这是我的代码:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  var cell: UITableViewCell = tableview.dequeueReusableCellWithIdentifier("cell") as UITableViewCell {     //Error
    cell.textLabel?.text = self.items[indexPath.row] //Error
    return cell;  //Error
  }
}

【问题讨论】:

    标签: swift initialization setter getter


    【解决方案1】:

    我认为您有一组额外的{},实际上,您正在定义一个块并将其分配给单元格变量:

    var cell: UITableViewCell = tableview.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
    cell.textLabel?.text = self.items[indexPath.row] //Error
    return cell;  //Error
    

    而且,由于dequeueReusableCell... 已经返回了一个 UITableViewCell,所以您真正需要的是:

    var cell = tableview.dequeueReusableCellWithIdentifier("cell")
    

    我猜你剪切/复制的代码开始看起来像:

    if let cell = tableview.dequeueReusableCellWithIdentifier("cell") as? MyCellClass {
        // some setup code here
        return cell
    }
    

    【讨论】:

    • 非常感谢,这正是我所需要的
    • @SonnySluiter 不要忘记将此答案标记为正确。这也是我的问题。从具有块的if let 开始,得到 if let 条件必须是 Optional 类型错误,将其删除并最终出现此错误。删除块是修复它的原因,我想很多人在修复我所做的同一个问题后也可能会遇到这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多