Will M. Will M. - 1 year ago 120
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>) {


Answer Source

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() {

But even simpler, use unsafeAddressOf():

func printMyPointer() {

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



    print(unsafeBitCast(self, to: UnsafeRawPointer.self))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download