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

A protocol's mutating keyword is enforced on AnyObject when using generics

    XMLWordPrintable

    Details

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

      Description

      The `mutating` keyword on protocols is enforced by the compiler on Object types when the type is given by a generic constraint. The `mutating` keyword is not otherwise enforced on objects.

      This is inconsistent, I think it should work in this case as well.

      Error:

      Cannot use mutating member on immutable value: 'base' is a 'let' constant.
      Fix-it     Change 'let' to 'var' to make it mutable
      

      Example

      protocol SomeProtocol {
          mutating func update()
      }
      struct ObjectWrapper<T: AnyObject> {
          let base: T
      }
      

      This works:

      struct Example: SomeProtocol { func update() { } }
      
      let x = ObjectWrapper(base: Example())
      x.base.update()
      

      This does not work:

      extension ObjectWrapper where T: SomeProtocol {
          func update() {
              self.base.update()
          }
      }
      

      This does not work:

      func update
          <S: Sequence where S.Iterator.Element: SomeProtocol, S.Iterator.Element: AnyObject>
          (sequence: S)
      {
          for element in sequence {
              let wrapper = ObjectWrapper(base: element)
              wrapper.base.update()
          }
      }
      
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              bnut Andrew Bennett
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: