Eric Pigeon
Eric Pigeon

Reputation: 1131

Swift self referencing class property

I am trying to create a self referencing class property in swift but I can't figure out why this isn't working. I really just want to use this as a key for dispatch_set_specific to manage an private dispatch queue.

class SomeClass{
    var ptr:UnsafePointer<Void> = nil

    init() {
        withUnsafePointer(&ptr, {
            self.ptr  = $0
        })
    }
}

Upvotes: 2

Views: 721

Answers (2)

Milosh Milivojevich
Milosh Milivojevich

Reputation: 19

This is how you do it.

self.ptr = UnsafePointer($0) <-Access to instance properties or methods

Swift permits and even encourages you to omit self keyword when it can be done. The challenge is to determine the scenarios when self is obligatory and when optional. In Swift self is a special property of an instance that holds the instance itself. Most of the times self appears in an initializer or method of a class, structure or enumeration.

Upvotes: 0

Martin R
Martin R

Reputation: 539715

Inside the closure $0 is a pointer to ptr and therefore has the type UnsafePointer<UnsafePointer<Void>>. You need to convert it to the type of ptr:

withUnsafePointer(&ptr, {
    self.ptr  = UnsafePointer($0)
})

This can also be written as:

ptr = withUnsafePointer(&ptr) { UnsafePointer($0) }

Any UnsafePointer<T> can be converted from a different UnsafePointer<U>:

/// Convert from a UnsafePointer of a different type.
///
/// This is a fundamentally unsafe conversion.
init<U>(_ from: UnsafePointer<U>)

and the type is inferred automatically from the context, so it is sufficient to write

UnsafePointer($0)

instead of

UnsafePointer<Void>($0)

Update for Swift 3:

var ptr = UnsafeRawPointer(bitPattern: 1)!

ptr = withUnsafePointer(to: &ptr) { UnsafeRawPointer($0) }

Upvotes: 4

Related Questions