Search code examples
swiftcompiler-errorsclosuresinout

Disable error that can be self righted using a inout with the `any <#AnyProtocol#>` type


I have been making a function that uses an inout on an any SomeProtocol but the compiler insists that it can’t allow it because "inout allows for input to be changed to another type" but I can make a function that prevents input to be changed and would like to know if I can by making my code slightly unsafe I can allow this error to side in someway?

My functions current signature is:

public func run(_ Targets:inout[Target], _ Params : Input, _ caller: inout Caller)throws -> Output

By using a closure I allow a user of the interface to define almost anything that they want to happen but it outputs an error. I have tried fixing it by making the input less well defined but equivocal to the type that must be inputted however that fails and produces a new error.


Solution

  • No. This is not possible.

    You will need to return a value rather than use an inout.

    Instead of this:

    func f(_ x: inout any SomeProtocol)
    ...
    f(&value)
    

    You would use this:

    func f(x: any SomeProtocol) -> any SomeProtocol
    ...
    value = f(value)
    

    That said, you should also re-evaluate whether you need any here. Changing any to some may also fix your problem, since some types are determined at compile time and do not risk type modification. For example:

    func f(_ x: inout some SomeProtocol)
    

    As a rule, if you can use some, you should.