Tulleb Tulleb - 4 months ago 69
Swift Question

Immutable value as inout argument

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...

Answer

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)