Skip to content

#require does not always fail correctly with if let #81027

Closed as duplicate of#79202
@davidbarry-kr

Description

@davidbarry-kr

Description

In Swift 6.1 using #require with an if let syntax produces an incorrect warning about redundant usage:

'#require(_:_:)' is redundant because 'container.text' never equals 'nil' (from macro 'require')

This is displayed when the function/property in question is indeed optional. Additionally in this case with an if let if the expression in the #require yields a nil value no failure is recorded. This is a regression from Swift 6.0 where a failure would still be recorded despite the use of try? along with #require.

Another wrinkle with this: if the expression inside the require is awaited (if let value = try? #require(await getSomeValue())) the warning will still appear, but it will correctly record a test failure when the value is nil.

Reproduction

This is a simplified example to show a compact reproduction of the problem. This test will pass despite the value being nil.

struct Container {
    var text: String? = nil
}

@Test
func example() {
    let container = Container()

    if let text = try? #require(container.text) {
        #expect(text == "some value")
    }
}

This does not demonstrate a good reason to use an if let with #require, but simply reproduces the problem. I've attached a package with more thorough examples of the problem as well as an example of when you may want to use if let with a #require.
The package also includes an example of identical code but an awaited expression which produces the same warning but which fails correctly when the test is run.

SwiftTestingRegression.zip

Expected behavior

  • The #require in the above example should generate a test failure.
  • The '#require(_:_:)' is redundant because 'container.text' never equals 'nil' (from macro 'require') warning should not be present.

Environment

Testing Library Version: 124

swift-driver version: 1.120.5 Apple Swift version 6.1 (swiftlang-6.1.0.110.21 clang-1700.0.13.3)
Target: arm64-apple-macosx15.0

Darwin OF060LKFWC4L02U 24.4.0 Darwin Kernel Version 24.4.0: Wed Mar 19 21:17:35 PDT 2025; root:xnu-11417.101.15~1/RELEASE_ARM64_T6041 arm64

Additional information

This warning and behavior appeared in Swift 6.1. The tests in the attached package will fail as expected and not generate warnings, in Swift 6.0.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions