Skip to main content

Using metatype Self to return current type

Updated:

A helpful keyword in Swift is Self, which is a metatype that represents the current type. The current type may be the class, subclass or current implementer of a protocol, depending on where it is used.

A handy use-case for it is to avoid specifying generic placeholder types. Neat!

class ThreadRobot<CallerT: CallerRobot> {
    private let app = XCUIApplication()

    func tapCompleteButton() -> Self {
        app.otherElements["actionButtonRail"].buttons["Complete"].tap()
        return self
    }
}

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

Thanks for reading!

Like what you read? Please share the article.

Avatar of Andrew Lord

WRITTEN BY

Andrew Lord

A software developer and tech leader from the UK. Writing articles that focus on all aspects of Android and iOS development using Kotlin and Swift.

Want to read more?

Here are some other articles you may enjoy.