Skip to content

Instantly share code, notes, and snippets.

@NikolaiRuhe
Created May 22, 2022 18:41
Show Gist options
  • Save NikolaiRuhe/b404f97fbacd1f8bd24e367af9b07a5b to your computer and use it in GitHub Desktop.
Save NikolaiRuhe/b404f97fbacd1f8bd24e367af9b07a5b to your computer and use it in GitHub Desktop.
Using a result builder to gather source code locations for unit testing.
// example unit test:
func testAscii() async throws {
locate {
"Celcius"
"Farenheit"
"Kelvin"
"yes?"
"no?"
"yes;no;cancel"
}.forEach { string, file, line in
let isAscii = string.allSatisfy { $0.isASCII }
XCTAssert(isAscii, "not ascii", file: file, line: line)
}
}
// impl:
public func locate<Value>(@LocatedValueBuilder<Value> content: () -> [(Value, StaticString, UInt)]) -> [(Value, StaticString, UInt)] {
return content()
}
@resultBuilder
public struct LocatedValueBuilder<Value> {
static func buildExpression(_ expression: Value, file: StaticString = #filePath, line: UInt = #line) -> (Value, StaticString, UInt) {
(expression, file, line)
}
static func buildBlock(_ components: (Value, StaticString, UInt)...) -> [(Value, StaticString, UInt)] {
Array(components)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment