Skip to content

Compiler unnecessarily requires mutating in protocol extensions where Self: AnyObject #77822

@fwcd

Description

@fwcd

Description

The compiler is unnecessarily restrictive regarding the requirement to declare protocol extension methods as mutating when it could already infer that the method is on a class.

Reproduction

Consider

protocol Wrapper { associatedtype Value var wrappedValue: Value { get set } } extension Wrapper where Self: AnyObject { func useValue(_ action: (inout Value) -> Void) { action(&wrappedValue) // Does not work } }

This produces

mutating-object-self.swift:8:16: error: cannot pass immutable value as inout argument: 'self' is immutable 5 | 6 | extension Wrapper where Self: AnyObject { 7 | func useValue(_ action: (inout Value) -> Void) { | `- note: mark method 'mutating' to make 'self' mutable 8 | action(&wrappedValue) // Does not work | `- error: cannot pass immutable value as inout argument: 'self' is immutable 9 | } 10 | } 

Expected behavior

Since the following version (extending AnyObject directly) compiles:

protocol Wrapper: AnyObject { associatedtype Value var wrappedValue: Value { get set } } extension Wrapper { func useValue(_ action: (inout Value) -> Void) { action(&wrappedValue) // Works } }

...I would expect the other variant to compile too.

Environment

swift-driver version: 1.115 Apple Swift version 6.0.2 (swiftlang-6.0.2.1.2 clang-1600.0.26.4)
Target: arm64-apple-macosx15.0

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    AnyObjectFeature → types: The `AnyObject` built-in typebugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfextensionFeature → declarations: `extension` declarationsgeneric constraintsFeature → generics: generic constraintsmutatingFeature → declarations → functions: Mutating functionsprotocolFeature → type declarations: Protocol declarationsswift 6.0type checkerArea → compiler: Semantic analysisunexpected errorBug: Unexpected error

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions