Uploaded image for project: 'Swift'
  1. Swift
  2. SR-11298

Writable property declaration in a conditional-conforming protocol extension has incorrect mutability

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Done
    • Component/s: Compiler
    • Labels:
      None

      Description

      Attached snippet:

      protocol Protocol {}
      // If constrained to class, it works
      // protocol Protocol: class {}
      
      class ClassA: Protocol {
          // Mutable instance property
          var property: String = ""
      }
      
      extension Protocol where Self: ClassA {
          // Mutable wrapper property
          var wrappingProperty: String {
              get { return property }
              set { property = newValue }
          }
      }
      
      let instance = ClassA()
      
      // Direct property access allowed
      instance.property = ""
      
      // error: Cannot assign to property: 'instance' is a 'let' constant
      instance.wrappingProperty = ""
      

      Because `wrappingProperty` is declared in a conditional conformance to `ClassA`, a class, `wrappingProperty` should be mutable, just like `property`.

      In fact, if `Protocol` is declared as `class`, the code compiles without error.

      Occurs in Swift 5.0 and 5.1.

      Additional example, this time a read only getter:

      protocol Protocol {}
      // If constrained to class, it works
      // protocol Protocol: class {}
      
      class ClassA: Protocol {
          // Mutable instance property
          var property: String = ""
      }
      
      extension Protocol where Self: ClassA {
          // Mutable wrapper property
          var wrappingProperty: String {
              get { return property }
              set { property = newValue }
          }
      }
      
      class ClassB {
          private var classA = ClassA()
          var classAReadOnly: ClassA {
              return classA
          }
      }
      let instance = ClassB()
      
      // Direct property access allowed
      instance.classAReadOnly.property = "A"
      
      // error: Cannot assign to property: 'classAReadOnly' is a get-only property
      instance.classAReadOnly.wrappingProperty = "B"
      
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              suyashsrijan Suyash Srijan
              Reporter:
              igormaka Igor Makarov
              Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: