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

Reference types can't call mutating functions declared in a protocol extension.

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Duplicate
    • Component/s: None
    • Labels:
      None
    • Environment:

      Both Xcode Version 7.3.1 (7D1014) and Xcode Version 8.0 beta 6 (8S201h)

      Description

      Surprisingly, I can't find another bug open for this.

      Suppose we have

      import Cocoa
      
      protocol Bar {
          var foo: NSViewController? { get set }
      }
      

      We then declare a function in a protocol extension to clear our variable. The function must be mutating or else the variable can't be cleared.

      extension Bar {
          mutating func _clear() {
              if let p = foo {
                  foo = nil
              }
          }
      }
      

      We can both implement and consume this protocol from a value type

      struct Quz: Bar {
          var foo: NSViewController? = nil
          mutating func qux() {
              self._clear()
          }
      }
      

      However the same is not true for a reference type

      final class Baz: NSViewController {
          var foo: NSViewController? = nil
          override func viewWillAppear() {
              self._clear() //error: cannot use mutating member on immutable value: 'self' is immutable
          }
      }
      

      There is actually no real workaround to this example. In general, the func can be made non-mutating (which doesn't work here) or the protocol can be constrained to reference types (preventing Qux from implementing it), or the reference type can be converted to a value type (not for subclasses of NSViewController).

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              drewcrawford Drew Crawford
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: