我只是想知道这两种定义变量的形式是否彼此不同.或者应该在某些特殊情况下使用. var string1: String { return "ok"}var string2: String = "ok" 第一种方法叫做 computed property: Classes, structures, and
var string1: String { return "ok" } var string2: String = "ok"第一种方法叫做 computed property:
Classes, structures, and enumerations can define computed properties, which do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
您使用的表单只为string1提供了一个getter,使其成为只读属性.
第二种方法通常是stored property:
A stored property is a constant or variable that is stored as part of an instance of a particular class or structure. Stored properties can be either variable stored properties (introduced by the var keyword) or constant stored properties (introduced by the let keyword).
在您的情况下,它是一个读写属性(使用var关键字声明).
根据具体情况应该使用哪个.但有时只能引入计算属性(例如,如果您提供扩展名).