Skip to main content

Articles, snippets and thoughts about code from Andrew Lord.

Protocol function that returns the Self type

Published on · Updated on
1 minute read

We may find situations in which we want a protocol function to return the current type, here the metatype Self can come in handy. In these situations rather than just returning the protocol type, we likely want to return the type that conforms to the protocol. An associated type can be added to the protocol that defaults to Self to achieve this. Pretty handy!

protocol ChatThreadsRobot {
    associatedtype ChatThreadsType: ChatThreadsRobot = Self

    func tapCreateThread() -> ChatThreadsType

extension ConnectionThreadsRobot: ChatThreadsRobot {
    func tapCreateThread() -> ConnectionThreadsRobot {
        return self

I hope the article was useful. If you have any feedback or questions please feel free to reach out to me on Twitter.

Thanks for reading and happy coding!

Like what you read? Please share the article.

Avatar of Andrew Lord

Hi, I hope you enjoyed the article. I am Andrew - a builder of apps and developer tools. Articles on the blog focus on all aspects of Android and iOS development using Kotlin and Swift.

Subscribe via RSS