How to add tuples together

时间:2019-03-17 22:56:48

标签: swift tuples

How can one add integer tuples together? I came across this post, but I am getting an error:

Argument type '(Int, Int)' does not conform to expected type 'Numeric'

When I try to use a tuple that I have within an array. I'm not familiar with generics so I'm not even sure where to begin to fix this function to fit my code. Any advice?

func calculate() {
    let testArray = [(0, 0), (0, 7), (7,7), (7,0)]
    let nearbyObjects = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
    // this is where I get the error message
    let sum = add(nearbyObjects[0])(testArray[0])
}

func add<T : Numeric>(_ a: T...) -> (_ b: T...) -> [T] {
    return { (b: T...) -> [T] in
        return zip(a, b).map { $0.0 + $0.1 }
    }
}

Ideally I'd like to be able to add two tuples from the array above. So, (7,7) + (1, -1) = (8, 6)

1 个答案:

答案 0 :(得分:1)

Try this out:

func +<T : Numeric>(_ a: (T, T), _ b: (T, T)) -> (T, T) {
  return (a.0 + b.0, a.1 + b.1)
}

let result = (7, 7) + (1, -1)
print(result) // (8, 6)