swift - Swift 中的计算属性和存储值属性有什么区别?

标签 swift xcode properties

问题:

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/

相关文章:

iphone - 访问Web服务器,获取目录中的所有文件

c# - 如何引用类(不是对象)的属性?

properties - 使用 dart 中的括号表示法访问对象的属性

java - 如何从 Spring messageSource 手动重新加载属性文件

ios - 如何在 ios 编程中使用地址簿 API 获取联系人?

ios - PBJVISION - 从cameraMode.Video切换到cameraMode.Photo时出错

ios - 我如何解析这个 JSON Pokemon 字典? Sprite 宝可梦 API (swift 3)

arrays - 我如何知道数组中元素的值是否已更改?

objective-c - 为什么选择 Emacs/Vim/Textmate? Xcode 还不够好吗?

swift - 如何检测 tvOS Remote 上的音量按钮按下