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
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
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
}