6
\$\begingroup\$

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 < size; i++)
        sum += (*a++) * (*b++);
    return sum;
}

and the translation to Swift:

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

    for (var i = 0; i < size; i++){
        sum += (a[i]) * (b[i]);
    }
return sum;
}
\$\endgroup\$
15
\$\begingroup\$

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]) -> 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).
\$\endgroup\$
  • \$\begingroup\$ But just for my knowledge, was my implementation correct from the functionality point of view? \$\endgroup\$ – Duarte Feb 8 '16 at 17:50
  • 1
    \$\begingroup\$ Yes, it looked correct, but can be considered "old fashioned" for use in Swift. \$\endgroup\$ – Robert Feb 8 '16 at 17:51
  • 1
    \$\begingroup\$ Also, C-style for loops won't work in future versions of Swift. \$\endgroup\$ – Tim Vermeulen Feb 13 '16 at 18:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.