Adding any two numberic tuples in swift

后端 未结 2 1541
旧时难觅i
旧时难觅i 2021-02-06 08:20

I have created one function to add tuples which looks like (Int, Int).

func + (x: (T, T), y: (T, T)) -> (T, T) {
    return (x.0 + y.0, x.1         


        
2条回答
  •  隐瞒了意图╮
    2021-02-06 08:53

    Tuples need to have their number of elements determined at compile time, thus a variadic-like function won't work. You'll need to add overrides for the + operator, for each tuple size you need to support:

    func + (x: (T, T), y: (T, T)) -> (T, T) {
        return (x.0 + y.0, x.1 + y.1)
    }
    
    func + (x: (T, T, T), y: (T, T, T)) -> (T, T, T) {
        return (x.0 + y.0, x.1 + y.1, x.2 + y.2)
    }
    
    func + (x: (T, T, T, T), y: (T, T, T, T)) -> (T, T, T, T) {
        return (x.0 + y.0, x.1 + y.1, x.2 + y.2, x.3 + y.3)
    }
    
    // and so on, ...
    

    Alternatively, you can switch to other data types, like arrays, which allow a dynamic number of items:

    infix operator ++ 
    
    func ++(_ lhs: [T], _ rhs: [T]) -> [T] {
        return zip(lhs, rhs).map { $0.0 + $0.1 }
    }
    
    print([10, 12, 16] ++ [11, 36, 25]) // [21, 48, 41]
    

    Caveats of this approach:

    • you need to use a different operator, since is + already defined for arrays, and it concatenates the arrays instead of individually summing the corresponding elements
    • if the two arrays have different sizes, then the result will have the size of the smaller arrays of the two input ones.

提交回复
热议问题