‘Self’ with a type argument

I’m trying to implement a general functor in Swift. Is there a way to create and return an instance of Self from a method where U is its type argument (as explained here: Type-oriented programming/Self at the type level - Wikibooks, open books for an open world)? I’m not 100% familiar with Swift’s associated types so I’m at my wits’ end here.

Looks like it might be simple but I don’t know that syntax. What have you tried?

Well, I tried using Self as the return type, as in the code linked to, but in Swift ‘Self’ is not the current type operator but a proper type (with the same type arguments) so the code won’t compile unless T=U.

I meant what Swift code have you tried? Because I don’t know how to read what’s at your link, I can’t offer advice.

Hi @phomola,
Looking at the code you are trying to convert to Swift, you need to post your code for anyone to help you, there could be something very trivial or an issue, but cannot speculate unless you share more details.


I think your main problem is ‘implement a general functor in Swift’… what, exactly, are you trying to do? Your starting point is confusing and clashes with Swift in a number of places (Swift does not, for instance, execute code after ‘return’, a ‘Maybe[T]’ would be, depending on circumstances, var myOptional: MyClass? (an optional instance of MyClass) or var myOptional: MyProtocol? etc)
Have a look at the functor code at this link which might fit your requirements.

As a general tip, because it will make your life easier: if you’re still a bit shaky with Swift, I’d advise you to step back from functors and become more familiar with the basics; this sounds as if you’re trying to solve too many problems at once.

This topic was automatically closed after 166 days. New replies are no longer allowed.