Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set & get value of pointer Swift

In Objetive-C when I want set/change value of pointer. I use

*pointer = value 

But In Swift, how to get/set value of pointer?

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.

23.03.2016 - Update code

var inputPixels:UnsafeMutablePointer<UInt32> = nil inputPixels = UnsafeMutablePointer<UInt32>(calloc(inputHeight * inputWidth, UInt(sizeof(UInt32)))) 
like image 470
Giang Avatar asked Sep 04 '14 08:09

Giang


People also ask

What does a good set look like in volleyball?

A good set is a ball delivered in between the antennas, and with one or two feet off the net. For both setters when a ball is in front of the hitter that gives a lead-up position that facilitates the hitter's approach. Learning how to set takes lots of time and practice.


2 Answers

You can work with pointers in Swift. There are UnsafePointer and UnsafeMutablePointer generic types.

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.

When you work with an UnsafeMutablePointer pointer type and want to assign some value to it you have to do the following:

  • check if points to some variable (not nil)
  • Assign your value to the memory property

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) 
like image 68
Kostiantyn Koval Avatar answered Oct 06 '22 01:10

Kostiantyn Koval


You should use pointee property instead of memory in Swift 3

pointer.pointee = value 
like image 22
Roman Avatar answered Oct 06 '22 00:10

Roman