Immutable value as inout argument

I would like to have a pointer as a class parameter. But when I try to encode init, I get 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 an instance of MyClass that can refer to the same "value". Then, when I edit this value in this class, it will change everywhere.

This is the first time I work with a pointer in Swift. I think I'm doing it wrong ...

+4
source share
2 answers

For those who have a mistake cannot pass immutable value as inout argument. Make sure your argument is not the first. The Inout type does not look like optional values.

+8
source

You can send a pointer when initializing the object:

class MyClass {
    var valuePointer: UnsafeMutablePointer<AnyObject?>

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

MyClass:

let obj = MyClass(value: &obj2)
+2

Source: https://habr.com/ru/post/1649296/


All Articles