Skip to content

feat: add reportIfNil to report unexpected nil values #165

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions Sources/IssueReporting/ReportIfNil.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/// Evaluates a value and reports an issue if it is nil.
///
/// - Parameters:
/// - value: The value to check for nil.
/// - message: A message describing the expectation.
/// - reporters: Issue reporters to notify if the value is nil.
/// - fileID: The source `#fileID` associated with the issue reporting.
/// - filePath: The source `#filePath` associated with the issue reporting.
/// - line: The source `#line` associated with the issue reporting.
/// - column: The source `#column` associated with the issue reporting.
/// - Returns: The optional value, unchanged.
@_transparent
public func reportIfNil<T>(
_ value: T?,
message: @autoclosure () -> String = "Unexpected nil value",
to reporters: [any IssueReporter]? = nil,
fileID: StaticString = #fileID,
filePath: StaticString = #filePath,
line: UInt = #line,
column: UInt = #column
) -> T? {

guard let value else {
withErrorReporting(
message(),
to: reporters,
fileID: fileID,
filePath: filePath,
line: line,
column: column
) {
throw NilValueError()
}
return nil
}

return value
}

public struct NilValueError: Error {
public init() {}
}
35 changes: 35 additions & 0 deletions Tests/IssueReportingTests/ReportIfNilTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#if canImport(Testing) && !os(Windows)
import Testing
import IssueReporting

@Suite
struct ReportIfNilTests {

@Test
func reportsIssueForNilValueWithDefaultMessage() {
withKnownIssue {
_ = reportIfNil(Optional<String>.none)
} matching: { issue in
issue.error is NilValueError &&
issue.description == "Caught error: NilValueError(): Unexpected nil value"
}
}

@Test
func reportsIssueForNilValueWithCustomMessage() {
withKnownIssue {
_ = reportIfNil(Optional<String>.none, message: "Custom nil message")
} matching: { issue in
issue.error is NilValueError &&
issue.description == "Caught error: NilValueError(): Custom nil message"
}
}

@Test
func doesNotReportIssueForNonNilValue() {
let value: String? = "non-nil"
#expect(reportIfNil(value) == "non-nil")
}
}

#endif