Swift Protocol get only settable?

前端 未结 6 723
一生所求
一生所求 2020-12-08 00:23

why can I do this without any error:

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

while I define this:

protocol          


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-08 01:18

    The behavior you are seeing on your code sample is called member hiding. Member hiding happens in object oriented languages when new a member is declared with the same name or signature of an inherited one, so by having: var objectId: Int in your struct implementation, you are effectively creating a new member called objectId and hiding the property inherited from the protocol.

    In order to honor the contract between your struct and your protocol, objectId could be declared as:

      let objectId: Int = 1
    

    or

    var objectId: Int {
            get {
                return 1
            }
        }
    

提交回复
热议问题