Immutable value as inout argument

 ̄綄美尐妖づ 提交于 2019-12-05 04:02:18

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.

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)

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!