MsrButterfly
MsrButterfly

Reputation: 1599

Define explicit generic methods in Swift

In C++, I can do this:

class foo {
    template <class bar>
    bar baz() {
        return bar()
    }
}

But when I try this in Swift:

class Foo {
    func baz<Bar>() -> Bar {
        return Bar()
    }
}

I got a syntax error that Swift does not support explicit generic method specialization.

Is there any similar implementations in Swift?

Upvotes: 2

Views: 663

Answers (3)

linuxfever
linuxfever

Reputation: 3823

I know this is an old post, but I run into the same problem. The solution I found was to create a dummy class whose instances are passed to my function (similarly to C++ overloading).

// the dummy class
class Type2Type<T> {
    typealias type = T
}

// the generic function
func myFunction<T>(Type2Type<T>) {
    //do stuff here
}    

and call the function as

myFunction(Type2Type<myClass>())

Hope it helps.

Upvotes: 0

Mari&#225;n Čern&#253;
Mari&#225;n Čern&#253;

Reputation: 15748

I don't know what exactly the code in C++ does. But you might use Type Constraints.

However still it does not make sense to me, because not each class has constructor with no parameters in Swift. So I came up with this code, but I am not sure if that helps:

protocol TypeWithEmptyConstructor {
    init()
}

class SomeClass {
    required init() {
    }
}

extension SomeClass: TypeWithEmptyConstructor { }

class Foo {
    func baz<Bar: TypeWithEmptyConstructor>() -> Bar {
        return Bar()
    }
}

Upvotes: 3

David Seiler
David Seiler

Reputation: 9725

I'm not a Swift expert by any means, but if you can't specialize at compile time then you have to specialize at runtime. Swift does have some reflection features, so try something like:

class Foo {
    func baz<T>() -> T {
        if(T.Type == Bar) {
            doOneThing()
        } else {
            doTheOtherThing()
        }
    }
}

That code is untested, and might not work. Good luck.

Upvotes: -1

Related Questions