问题:
Row.swift 中这两行有什么区别?
上下文:
行.swift
open class Row {
// Existing code (Good):
public var cellIdentifier: String { return String(describing self) }
// The change (Bad):
public var cellIdentifier: String = String(describing: self)
DifferentRow.swift
public class DifferentRow: Row {
public override var cellIdentifier: String { return "\(super.cellIdentifier)" }
// returns the error below
错误:
无法使用只读属性“cellIdentifier”覆盖可变属性
最佳答案
这个:
public var cellIdentifier: String { return String(describing self) }
正在定义一个计算属性。不存储任何值。每次访问 cellIdentifier
时,闭包都会运行并返回 String
。它是只读的,因为只提供了 getter。
这个:
public var cellIdentifier: String = String(describing: self)
是一个存储值属性,它是可读/可写的。
错误告诉您不能将具有读/写功能的属性替换为仅具有读取功能的属性。
注意:如果您正在用一个值初始化一个属性,您不能访问self
,因为self
不代表类/struct instance 直到对象完全初始化。如果将属性设置为 lazy var
,则可以在初始化时使用 self
,因为这样属性会在第一次访问时被初始化。
您可以阅读有关 Swift 属性的更多信息 here in the Swift Language Guide
关于swift - Swift 中的计算属性和存储值属性有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52079148/