Access the call site of a function using special Swift literals
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!
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
Want to read more?
Here are some other articles you may enjoy.
Clear and searchable logging in Swift with OSLog
Logging is a useful tool for diagnosing issues and working out what an app is doing. We will explore Apple's currently recommended way of logging via OSLog, covering how to use it and managing its differences when compared to other logging approaches.