mixel mixel - 2 months ago 13
Swift Question

Swift tuple in where clause

I have generic class:

class Generic<T> {
var value: T

init(value: T) {
self.value = value
}
}


And I want to write extension method that only used if
T
is tuple of 2 values of any types and this method returns value of
Generic
type with new tuple of 3 values. I tried:

extension Generic {
func append<A, B, C where T: (A, B)>(c: C) -> Generic<(A, B, C)> {
return Generic(value: (value.0, value.1, c))
}
}


But obviously this is not working because
where
clause accepts only protocols.

Answer

The only way I found to implement it is:

class Generic<T> {
    var value: T

    init(value: T) {
        self.value = value
    }
}

protocol Tuple2 {
    typealias A
    typealias B
    var i0: A { get }
    var i1: B { get }
}

protocol Tuple3: Tuple2 {
    typealias C
    var i2: C { get }
}

struct Tuple2Impl<A, B>: Tuple2 {
    var i0: A
    var i1: B

    init(_ i0: A, _ i1: B) {
        self.i0 = i0
        self.i1 = i1
    }
}
struct Tuple3Impl<A, B, C>: Tuple3 {
    var i0: A
    var i1: B
    var i2: C

    init(_ i0: A, _ i1: B, _ i2: C) {
        self.i0 = i0
        self.i1 = i1
        self.i2 = i2
    }
}

extension Generic where T: Tuple2 {
    func append<C>(c: C) -> Generic<Tuple3Impl<T.A, T.B, C>> {
        return Generic<Tuple3Impl<T.A, T.B, C>>(value: Tuple3Impl(value.i0, value.i1, c))
    }
}

var a = Generic(value: Tuple2Impl("Hello", 256))

print(a.append(3.14).value.i2)