string - swift 中定义字符串变量的两种方式

标签 string swift variables

我只是想知道这两种定义变量的形式是否彼此不同。或者应该在某些特殊场景下使用。

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 关键字声明)。


什么时候应该使用取决于具体情况。但有时只能引入计算属性(例如,如果您提供扩展)。

关于string - swift 中定义字符串变量的两种方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33717937/

相关文章:

ios - 无法让 myDescription 值显示在 MainLabel、JSON API 上

python - 在 Python 中,如何检查变量是否存在?

java - Android "Global Variables"不持久

c - 如何扫描用户的字数并打印字符串?

ios - Collection View 单元格内容未显示

swift - 在 Swift 中转换为泛型可选

python - 您可以在不实例化变量的情况下在 Python 中创建变量列表吗?

R 表达式变量列表

javascript - 使用正则表达式获取括号内的字符串,删除括号

java - java中如何在字符串的字符两侧添加空格?