如何在Swift中创建一个指向自身的静态指针变量? [英] How to create a static pointer variable to itself in Swift?
问题描述
在Objective-C中,我经常使用使用static void*
作为标识标签的模式.有时,这些标签仅在该函数/方法中使用,因此将变量放置在函数内部很方便.
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 convenient to place the variable inside the function.
例如:
MyObscureObject* GetSomeObscureProperty(id obj) {
static void* const ObscurePropertyTag = &ObscurePropertyTag;
MyObscureObject* propValue = objc_getAssociatedObject(id,ObscurePropertyTag);
if(!propValue) {
propValue = ... // lazy-instantiate property
objc_setAssociatedObject(obj,ObscurePropertyTag,propValue, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return propValue;
}
问题是,如何在Swift中自行编写ObscurePropertyTag
私有常量指针? (最好是2.1,但将来已经发布的版本应该可以)
The question is, how to write the ObscurePropertyTag
private-constant-pointer-to-itself in Swift? (Preferrably 2.1 but future already-announced versions should be okay)
我环顾四周,似乎我必须将此ObscurePropertyTag
用作成员变量,并且似乎没有解决方法.
I've looked around and it seems that I have to put this ObscurePropertyTag
as a member variable and there doesn't seem to be a way around it.
推荐答案
与(Objective-)C不同,您不能使用 Swift中的未初始化变量.因此,创建一个自引用 指针是一个两步过程:
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:
迅速2:
var ptr : UnsafePointer<Void> = nil
withUnsafeMutablePointer(&ptr) { $0.memory = UnsafePointer($0) }
快捷键3:
var ptr = UnsafeRawPointer(bitPattern: 1)!
ptr = withUnsafePointer(to: &ptr) { UnsafeRawPointer($0) }
出于您的目的,将 global 变量的地址与&
一起使用是否更容易,请参见
例子
For your purpose, is it easier to use the address of a global variable with &
, see for
example
如果您想将标签"的范围限制为函数本身
那么您可以在本地struct
中使用 static 变量.示例:
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
}
这篇关于如何在Swift中创建一个指向自身的静态指针变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!