0

Most of the Swift SIMD float types have +-*/ operators, so we can just calculator the sum like below:

import simd

float2(2.0) + float2(2.0) // float2(4.0, 4.0)
float4(2.0) + float4(2.0) // float4(4.0, 4.0, 4.0, 4.0)

Now, Lets say I have a generic function that takes a pair of float2, float3 or float4 as arguments and returns the sum of them:

func calculateSum<T: SomeProtocolCoversThoseFloats>(a: T, b: T) -> {
    return a + b
}

Is there any protocol that functions like this "SomeProtocolCoversThoseFloats" or is there any way that I can create such a protocol?

hagmas
  • 19
  • 5
  • The same technique as in http://stackoverflow.com/questions/25575513/what-protocol-should-be-adopted-by-a-type-for-a-generic-function-to-take-any-num can be applied here. – Martin R Nov 05 '15 at 06:41
  • Ah that's a cool stuff and exactly what I wanted to do...! Thank you so much guys. :) – hagmas Nov 05 '15 at 07:14

2 Answers2

2

David is going the right direction, such a protocol doesn't exist (simd is from C and C doesn't have protocols, no surprise), but you can just declare one yourself. To make it so you can use +-*/, you have to add them to the protocol:

import simd

protocol ArithmeticType {
    func +(lhs: Self, rhs: Self) -> Self
    func -(lhs: Self, rhs: Self) -> Self
    func *(lhs: Self, rhs: Self) -> Self
    func /(lhs: Self, rhs: Self) -> Self
}

extension float4 : ArithmeticType {}
extension float3 : ArithmeticType {}
extension float2 : ArithmeticType {}

func sum<T: ArithmeticType>(a: T, b: T) -> T {
    return a + b
}

You can also extend Double, Float, Int, etc. if you need to

Kametrixom
  • 14,673
  • 7
  • 45
  • 62
1

If there isn't (and there doesn't appear to be), it's easy enough to add your own:

protocol SimdFloat {}

extension float2 : SimdFloat {}
extension float3 : SimdFloat {}
extension float4 : SimdFloat {}

This doesn't really directly solve your problem, however as it doesn't declare that two SimdFloat's implement +.

David Berry
  • 40,941
  • 12
  • 84
  • 95
  • You have to add `func +(lhs: Self, rhs: Self) -> Self` etc to the protocol definition. – Martin R Nov 05 '15 at 06:29
  • Yeah, I was just trying that, wasn't sure I could add operators to a protocol. And before I could update the answer... stack overflow forgot who I was... At this point, it's easiest to just late Kame's answer go :) – David Berry Nov 05 '15 at 06:37