Swift generics and specialization

Viewed 1372

I realize Swift generics are not like C++ templates where the code is specialized and generated at instantiation, but is there a way to get the following code to specialize the second call?

func X1<R>(i: R) {
    print("R")
}

func X1(i: Int) {
    print("Int")
}

func X2<R>(i: R) {
    X1(i: i)
}

X2(i: "s")
X2(i: 1)
X1(i: "s")
X1(i: 1)

In particular, the output I see is:

R
R
R
Int

But I really want the X2 call to X1 for Int to specialize to the X1 Int:

R
Int
R
Int

I know I can do it by creating another X2 with Int as the type, but I was hoping to avoid that.

EDIT A few of the answers suggests adding handling per specialized type (i.e., add a func X2(i: Int) or doing type casting let x = i as? Int) -- that's what I'm trying to avoid as there could be a lot of specialized types, for example:

func X1(i: Double) {
    print("Double")
}

func X1(i: Bool) {
    print("Bool")
}

func X1(i: Float) {
    print("Float")
}
2 Answers
Related