Skip to main content

Access the call site of a function using special Swift literals

Updated:

Accessing information about the call site of a function is surprisingly simple in Swift by simply using #file, #function and #line. This can be a great help when we want to put assertions within a shared function or print text without losing the original context.

extension  XCTestCase {
    struct UnexpectedNilError: Error {}

    func unwrapAssert<ValueT>(_ value: ValueT?,
                              message: String = "Unexpected nil",
                              file: StaticString = #file,
                              line: UInt = #line) throws -> ValueT {
        guard let value = value else {
            XCTFail(message, file: file, line: line)
            throw  UnexpectedNilError()
        }
        return value
    }
}

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.