Skip to main content

Articles, snippets and thoughts about code from Andrew Lord.

Access the call site of a function using special Swift literals

Published on · Updated on
1 minute read

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 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