我试图迅速创建一个自引用类属性,但我不知道为什么这不起作用。我真的只想使用它作为dispatch_set_specific的键来管理 private 调度队列。

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

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

最佳答案

在闭包内部$0是指向ptr的指针,因此具有类型UnsafePointer<UnsafePointer<Void>>。您需要将其转换为ptr的类型:

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

也可以写成:
ptr = withUnsafePointer(&ptr) { UnsafePointer($0) }

可以从其他UnsafePointer<T>转换任何UnsafePointer<U>:
/// Convert from a UnsafePointer of a different type.
///
/// This is a fundamentally unsafe conversion.
init<U>(_ from: UnsafePointer<U>)

并且根据上下文自动推断出类型,因此编写该代码就足够了
UnsafePointer($0)

代替
UnsafePointer<Void>($0)

Swift 3的更新:
var ptr = UnsafeRawPointer(bitPattern: 1)!

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

关于ios - Swift自引用类属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27426335/

10-11 06:59