[swift-users] Conditional generic initializers?

Neil Faiman neil.swift at faiman.org
Sun May 15 07:45:15 CDT 2016


Is it possible for a generic class to have methods (specifically, initializers) which are only defined if the generic parameters meet certain constratins?

Here’s a concrete example:

    class Foo <T1, T2> {
        init(pairs: [(T1, T2)]) {}
        // What I’d like to be able to doL
        convenience init "where T1 == T2" (values: [T1]) { self.init(pairs: values.map{ ($0, $0) }) }
    }

That is, I’d like to provide a convenience initializer that takes an array of values instead of pairs, and turns the values into pairs, IF THE TWO GENERIC TYPE PARAMETERS ARE THE SAME.

I can’t find a way to accomplish this. Is there one?

Thanks,

	Neil Faiman


More information about the swift-users mailing list