Swift协议只能设置吗? [英] Swift Protocol get only settable?

查看:61
本文介绍了Swift协议只能设置吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我可以做到这一点而没有任何错误:

why can I do this without any error:

var testDto = ModelDto(modelId: 1)
testDto.objectId = 2

在我定义这个的时候:

protocol DataTransferObject {
    var objectType: DtoType { get }
    var parentObjectId: Int { get set }
    var objectId: Int { get }
    var objectName: String { get set }
}

struct ModelDto: DataTransferObject {
    var objectType: DtoType
    var parentObjectId: Int
    var objectId: Int
    var objectName: String

    init(modelId: Int) {
        self.objectType = DtoType.Model
        self.objectId = modelId
        self.parentObjectId = -1
        self.objectName = String()
    }
}

如果协议中的定义大多被忽略(getter,setter定义),为什么我仍然要使用它们?

If the definition in my protocol is mostly ignored (getter, setter definition), why should I use them anyway?

推荐答案

根据符合类型可以通过多种方式来满足getter和setter要求.如果属性声明同时包含get和set关键字,则符合条件的类型可以使用存储的变量属性或既可读又可写的计算属性(即,同时实现getter和setter的)来实现它.但是,该属性声明不能实现为常量属性或只读的计算属性. 如果属性声明仅包含get关键字,则可以将其实现为任何类型的属性.

The getter and setter requirements can be satisfied by a conforming type in a variety of ways. If a property declaration includes both the get and set keywords, a conforming type can implement it with a stored variable property or a computed property that is both readable and writeable (that is, one that implements both a getter and a setter). However, that property declaration can’t be implemented as a constant property or a read-only computed property. If a property declaration includes only the get keyword, it can be implemented as any kind of property.

这篇关于Swift协议只能设置吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆