ios 如何设置和获取指针 Swift 的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25660299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set & get value of pointer Swift
提问by Giang
In Objetive-C when I want set/change value of pointer. I use
在 Objetive-C 中,当我想设置/更改指针值时。我用
*pointer = value
But In Swift, how to get/set value of pointer?
但是在 Swift 中,如何获取/设置指针的值?
I'm woking with bitmap pixel:
我正在使用位图像素:
NSUInteger offsetPixelCountForInput = ghostOrigin.y * inputWidth + ghostOrigin.x;
for (NSUInteger j = 0; j < ghostSize.height; j++) {
for (NSUInteger i = 0; i < ghostSize.width; i++) {
UInt32 * inputPixel = inputPixels + j * inputWidth + i + offsetPixelCountForInput;
UInt32 inputColor = *inputPixel;
newR = MAX(0,MIN(255, newR));
newG = MAX(0,MIN(255, newG));
newB = MAX(0,MIN(255, newB));
*inputPixel = RGBAMake(newR, newG, newB, A(inputColor));
}
}
So I want to convert this code into Swift, but I'm stuck with pointers.
所以我想把这段代码转换成 Swift,但我被指针困住了。
23.03.2016 - Update code
23.03.2016 - 更新代码
var inputPixels:UnsafeMutablePointer<UInt32> = nil
inputPixels = UnsafeMutablePointer<UInt32>(calloc(inputHeight * inputWidth, UInt(sizeof(UInt32))))
回答by Kostiantyn Koval
You can work with pointers in Swift. There are UnsafePointer
and UnsafeMutablePointer
generic types.
您可以在 Swift 中使用指针。有UnsafePointer
和UnsafeMutablePointer
泛型类型。
Here is a function that takes a float
pointer
You can use float variable and pass it's address &floatVar
or you can create and allocate an UnsafeMutablePointer
and pass it. But you have to manually allocate and deallocate memory.
这是一个带有float
指针的函数
您可以使用浮点变量并传递它的地址,&floatVar
或者您可以创建并分配一个UnsafeMutablePointer
并传递它。但是您必须手动分配和释放内存。
When you work with an UnsafeMutablePointer
pointer type and want to assign some value to it you have to do the following:
当您使用UnsafeMutablePointer
指针类型并希望为其分配一些值时,您必须执行以下操作:
- check if points to some variable (not nil)
- Assign your value to the
memory
property
- 检查是否指向某个变量(非零)
- 将您的价值分配给该
memory
物业
Code Example:
代码示例:
func work (p: UnsafeMutablePointer<Float>) {
if p != nil {
p.memory = 10
}
println(p)
println(p.memory)
}
var f: Float = 0.0
var fPointer: UnsafeMutablePointer<Float> = UnsafeMutablePointer.alloc(1)
work(&f)
work(fPointer)
fPointer.dealloc(1)
回答by Roman
You should use pointeeproperty instead of memoryin Swift 3
您应该在 Swift 3 中使用指针属性而不是内存
pointer.pointee = value