Why can't a get-only property requirement in a protocol be satisfied by a property which conforms?

后端 未结 2 1167
孤城傲影
孤城傲影 2020-11-22 05:23

Why does the following code produce an error?

protocol ProtocolA {
    var someProperty: ProtocolB { get }
}

protocol ProtocolB {}
class ConformsToB: Protoc         


        
2条回答
  •  执笔经年
    2020-11-22 06:17

    In addition to Harmish's great response, if you want to keep using the same property name on both SomeClass and ProtocolA, you can do

    protocol ProtocolB {}
    
    protocol ProtocolA {
        var _someProperty_protocolA: ProtocolB { get }
    }
    
    extension ProtocolA {
        var someProperty: ProtocolB {
            return _someProperty_protocolA
        }
    }
    
    class ConformsToB: ProtocolB {}
    
    class SomeClass: ProtocolA {
    
    
        // the *actual* implementation of someProperty.
        var _someProperty: ConformsToB
    
        var someProperty: ConformsToB {
          // You can't expose someProperty directly as
          // (SomeClass() as ProtocolA).someProperty would
          // point to the getter in ProtocolA and loop
          return _someProperty
        }
    
        // dummy property to satisfy protocol conformance.
        var _someProperty_protocolA: ProtocolB {
            return someProperty
        }
    
        init(someProperty: ConformsToB) {
            self.someProperty = someProperty
        }
    }
    
    let foo = SomeClass(someProperty: ConformsToB())
    // foo.someProperty is a ConformsToB
    // (foo as ProtocolA).someProperty is a ProtocolB
    

    This can be useful when you are conforming to another protocol ProtocolA2 that would originally also have constraint on someProperty as well, or when you want to hide your hack around swift limitations.

    I'm now curious to know why Swift is not doing this for me directly.

提交回复
热议问题