Skip to content

#require broken when accessing optional property #623

Closed
@macguru

Description

@macguru

Description

The following code does not compile currently. It produces an incorrect warning and an error inside the #expect macro compilation:

protocol MyType {
    func function() -> Something
}

protocol Something {
    var optional: Any? { get }
}

@MainActor @Test func mainExample() throws {
    let object: MyType?
    _ = try #require(object?.function().optional) // Warning: No calls to throwing functions occur within 'try' expression
    // Error: Value of optional type '(any Something)?' must be unwrapped to a value of type 'any Something'
}

As far as my testing goes, this needs a chaining of three things inside the #require:

  • an optional base value
  • a function returning a non-optional value (which is transitively optional, because of the base)
  • an optional property defined on the function's return value

I tried to be general here, but a common scenario is some object that has a function like makeArray() -> [Int] which is then accessed using first (e.g because we know there's just one element in this particular situation).

Expected behavior

The code should compile. The workaround is to split this into two expectations at any point in the chain. For example like so:

@MainActor @Test func mainExample() throws {
    let object: MyType?
    let some = try #require(object?.function())
    _ = try #require(some.optional)
}

Actual behavior

No response

Steps to reproduce

No response

swift-testing version/commit hash

Xcode 16 beta 5

Swift & OS version (output of swift --version ; uname -a)

swift-driver version: 1.113 Apple Swift version 6.0 (swiftlang-6.0.0.7.6 clang-1600.0.24.1)
Target: arm64-apple-macosx15.0
Darwin Mac.localdomain 24.0.0 Darwin Kernel Version 24.0.0: Wed Aug 7 03:08:56 PDT 2024; root:xnu-11215.1.9~22/RELEASE_ARM64_T6020 arm64

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug🪲 Something isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions