加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

两种在swift中定义字符串变量的方法

发布时间:2020-12-14 04:37:07 所属栏目:百科 来源:网络整理
导读:我只是想知道这两种定义变量的形式是否彼此不同.或者应该在某些特殊情况下使用. var string1: String { return "ok"}var string2: String = "ok" 解决方法 第一种方法叫做 computed property: Classes,structures,and enumerations can define computed pro
我只是想知道这两种定义变量的形式是否彼此不同.或者应该在某些特殊情况下使用.

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

根据具体情况应该使用哪个.但有时只能引入计算属性(例如,如果您提供扩展名).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读