How to create a static pointer variable to itself in Swift?

前端 未结 2 1767
醉酒成梦
醉酒成梦 2021-01-22 05:55

In Objective-C I often use the pattern of using a static void* as an identification tag. At times these tags are only used within that function/method, hence it\'s

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-22 06:24

    Unlike (Objective-)C, you cannot take the address of an uninitialized variable in Swift. Therefore creating a self-referencing pointer is a two-step process:

    Swift 2:

    var ptr : UnsafePointer = nil
    withUnsafeMutablePointer(&ptr) { $0.memory = UnsafePointer($0) }
    

    Swift 3:

    var ptr = UnsafeRawPointer(bitPattern: 1)!
    ptr = withUnsafePointer(to: &ptr) { UnsafeRawPointer($0) }
    

    For your purpose, is it easier to use the address of a global variable with &, see for example

    • Is there a way to set associated objects in Swift?.

    If you want to restrict the scope of the "tag" to the function itself then you can use a static variable inside a local struct. Example:

    func obscureProperty(obj : AnyObject) -> MyObscureObject {
        struct Tag {
            static var ObscurePropertyTag : Int = 0
        } 
        if let propValue = objc_getAssociatedObject(obj, &Tag.ObscurePropertyTag) as? MyObscureObject {
            return propValue
        }
        let propValue = ... // lazy instantiate property value
        objc_setAssociatedObject(obj, &Tag.ObscurePropertyTag,propValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        return propValue
    }
    

提交回复
热议问题