nielsbot
nielsbot

Reputation: 16031

Can I specialize a generic function on a type passed as a parameter?

I want to be able to specialize a generic function by passing a type as an argument, instead of having to declare a variable having the desired type and writing an assignment to that variable.

In my use case, I'm walking up the responder chain looking for an object that conforms to a certain protocol. If found, I'd like to call a method on that object.

I'm trying to do it in a "swift-y" (i.e. type safe) way.

The code I'm currently using looks like this:

if let r:UndoManager = self.findResponder() {
    r.undo(...)
}

but that makes it hard to chain in a statement.

I want to do something more succinct, like the following, passing the desired protocol as an argument to my function.

self.findResponder( UndoManager )?.undo(...)

In this example, say I have protocol UndoManager, defined as

protocol UndoManager {
    func undo(...)
}

Also, my declaration of findResponder() currently looks like

public extension NSReponder {
    public func findResponder<T>() -> T? {
        ...
    }
}

Upvotes: 0

Views: 214

Answers (1)

rintaro
rintaro

Reputation: 51911

If you want to do self.findResponder( UndoManager )?.undo(...) instead of (findResponder() as Undo?)?.undo(...), the method signature would be:

    public func findResponder<T>(_: T.Type) -> T? {
        // ...
    }

Upvotes: 1

Related Questions