Dot product, ported from C to Swift This is how I posted a method from C to Swift. I tested it well, it seems to work. It's there a way to write this better, following good practices of Swift? The original is in C and the target must be in Swift.

Original C Code:


inline float mac(const float *a, const float *b, unsigned int size)
{
    float sum = 0;
    unsigned int i;

    for (i = 0; i &lt; size; i++)
        sum += (*a++) * (*b++);
    return sum;
}



and the translation to Swift:

func mac(a : [Float], b : [Float], size : Int) -&gt; Float
{
    var sum : Float = 0;

    for (var i = 0; i &lt; size; i++){
        sum += (a[i]) * (b[i]);
    }
return sum;
}
You can remove the size parameter as arrays know their own size in Swift, and use the zip, map and reduce functions to perform the computation rather than the C-style for loop, which is now unavailable in the latest versions of Swift (as is i++):

func mac(a: [Float], b: [Float]) -&gt; Float {
    return zip(a, b).map(*).reduce(0, +)
}



The zip function takes two arrays and makes a single array of tuples, with each tuple containing the nth element from each array.
The map function changes each element of the array with a user-supplied function. In this case, the multiplication operator is passed in, which multiplies each pair.
The reduce function performs the task of summing each result (starting at 0).