Will M. Will M. - 3 months ago 39
Swift Question

Printing &self in swift, cannot assign to immutable value of type

This is just an exercise in pointers in swift, but I was trying to write a function that would print the pointer to self, but I kept getting an error "cannot assign to immutable value of type C". Is this something that is even possible in Swift?

class C {
static var c = C()
var a = 1
func printMyPointer() {
printPointer(&self) //cannot assign to immutable value of type C
}

func printPointer(ptr:UnsafePointer<C>) {
print(ptr)
}
}

C.c.printMyPointer()

Answer

As already explained in the other answer, you cannot pass a constant as the argument for an in-out parameter. As a workaround, you can pass an array, as this will actually pass the address of the first element:

func printMyPointer() {
    printPointer([self])
}

But even simpler, use unsafeAddressOf():

func printMyPointer() {
    print(unsafeAddressOf(self))
}

*Update for Swift 3:** As of Xcode 8 beta 6, unsafeAddressOf does not exist anymore. You can convert self to a pointer:

    print(Unmanaged.passUnretained(self).toOpaque())

or

    print(unsafeBitCast(self, to: UnsafeRawPointer.self))