juppy - 2 years ago 78

Swift Question

I use a C library in my Swift application and I cannot figure out how to get the multidimensional array that the C method is supposed to return.

I receive this from the C API:

`struct resultArray`

{

double *data;

int size[2];

};

Where:

size = the matrix size, a two element array with the number of rows and number of columns

data = the matrix data

In swift I can do the following to get the size:

`let numRows = Int(results.size.0)`

let numColoumns = Int(results.size.1)

But I don't understand how to get the matrix so that I can iterate through it? I tried the following:

`let matrixResult = results.data.memory`

This seems to return only a double value because matrixResult becomes a Double.

Then I tried this:

`let matrixResult = results.data`

Which makes the matrixResult an:

`UnsafeMutablePointer<Double>`

I expect to receive a matrix as specified in the C library documentation. Then I want to iterate through this matrix and get the values from the first row and put it in a Swift array... Does somebody know what I am missing here?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

There is no *matrix* type in C. Assuming that `data`

is a pointer to
the contiguous matrix elements stored as an *array*, you would copy the
first row to a Swift array with

```
let firstRow = Array(UnsafeBufferPointer(start: results.data, count: numColumns))
```

and the entire "matrix" to a nested Swift array with

```
let matrix = (0 ..< numRows).map { row in
Array(UnsafeBufferPointer(start: results.data + numColumns * row, count: numColumns))
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**