1

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()
Will M.
  • 1,864
  • 17
  • 28

2 Answers2

7

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))
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thanks! I actually stumbled upon unsafeAddressOf a few seconds before this post, but I didn't know about the array workaround. – Will M. Jun 30 '15 at 17:59
2

From the Swift Docs:

You can only pass a variable as the argument for an in-out parameter. You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified. You place an ampersand (&) directly before a variable’s name when you pass it as an argument to an inout parameter, to indicate that it can be modified by the function.

Since self is immutable, you can't pass it as an inout parameter. Even though the method signature dosen't use inout, Swift treats pointer parameters like inout, according to the Swift blog:

Swift allows pointer parameters to be treated like inout parameters, so you can pass a reference to a var as a pointer argument by using the same & syntax.

  • I see. Is it possible to get the address of a variable without indicating it as an inout parameter? – Will M. Jun 30 '15 at 17:55