-->

Immutable value as inout argument

2020-08-24 05:59发布

问题:

I would like to have a pointer as a parameter of a class. But when I am trying to code the init, I am having this error: Cannot pass immutable value of type 'AnyObject?' as inout argument

class MyClass {
    var valuePointer: UnsafeMutablePointer<AnyObject?>

    init(value: inout AnyObject?) {
        self.valuePointer = &value
    }
}

I would like to create some instance of MyClass which can all refer to the same "value". Then, when I am editing this value in this class, it would change everywhere else.

This is the first time I'm working with pointer in Swift. I guess I am doing it wrong...

回答1:

For those who has the cannot pass immutable value as inout argument error. Check that your argument is not optional first. Inout type doesn't seems to like optional values.



回答2:

You could send the pointer when initializing the object:

class MyClass {
    var valuePointer: UnsafeMutablePointer<AnyObject?>

    init(value: inout UnsafeMutablePointer<AnyObject?>) {
        self.valuePointer = value
    }
}

Just add the pointer reference when initializing MyClass:

let obj = MyClass(value: &obj2)


回答3:

For me, I had a class variable defined like this:

// file MyClass.swift

class MyClass{

    var myVariable:SomeClass!

    var otherVariable:OtherClass!

    ...

    func someFunction(){
        otherVariable.delegateFunction(parameter: &myVariable) // error
    }
}

// file OtherClass.swift
class OtherClass{
    func delegateFunction(parameter: inout myVariable){
        // modify myVariable's data members 
    }
}

There error that was invoked was:

Cannot pass immutable value as inout argument: 'self' is immutable

I then changed my variable declaration in MyClass.swift to no longer have ! and instead initially point to some dummy instance of a class.

var myVariable:SomeClass = SomeClass() 

My code was then able to compile and run as intended. So... somehow having the ! on a class variable prevents you from passing that variable as an inout variable. I do not understand why.



回答4:

For someone faced the same issue with me:

Cannot pass immutable value as inout argument: implicit conversion from '' to '' requires a temporary

The code as below:

protocol FooProtocol {
    var a: String{get set}
}

class Foo: FooProtocol {
    var a: String
    init(a: String) {
        self.a = a
    }
}

func update(foo: inout FooProtocol) {
    foo.a = "new string"
}

var f = Foo(a: "First String")
update(foo: &f)//Error: Cannot pass immutable value as inout argument: implicit conversion from 'Foo' to 'FooProtocol' requires a temporary

Change from var f = Foo(a: "First String") to var f: FooProtocol = Foo(a: "First String") fixed the Error.