Skip to content

Compiler warnings for opaque return types do not explain the problem fully, making it hard to understand #80226

Open
@bolsinga

Description

@bolsinga

Description

I'm trying to write code that should return a sequence of values, based upon a condition. The return types are the same. The funnel function cannot return one of the two separate functions conditionally without a compiler error.

Reproduction

func typeA() -> some AsyncSequence<Int, Never> {
  let (stream, continuation) = AsyncStream<Int>.makeStream()
  Task.detached {
    defer { continuation.finish() }
    for taggedDB in 0..<3 {
      continuation.yield(taggedDB)
    }
  }
  
  return stream
}

func typeB() -> some AsyncSequence<Int, Never> {
  let (stream, continuation) = AsyncStream<Int>.makeStream()
  Task.detached {
    defer { continuation.finish() }
    for taggedDB in 0..<4 {
      continuation.yield(taggedDB)
    }
  }
  return stream
}

// The compiler points to this function declaration with the error message:
// Function declares an opaque return type 'some AsyncSequence<Int, Never>', but the return statements in its body do not have matching underlying types
func type() -> some AsyncSequence<Int, Never> {
  if Int.random(in: 0...10) % 2 != 0 {
    return typeA() // Error here is: Return statement has underlying type 'some AsyncSequence<Int, Never>'
  } else {
    return typeB() // Error here is: Return statement has underlying type 'some AsyncSequence<Int, Never>'
  }
}

Expected behavior

I expect this to be able to compile, but it's quite likely I'm not understanding something correctly.

Environment

swift-driver version: 1.115.1 Apple Swift version 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1)
Target: arm64-apple-macosx15.0

Additional information

I know the functions typeA and typeB are similar, but in my real world case, their implementations are quite different. So generalizing those would not really apply for me. This example is just the first simplified version of the problem I was able to get to. Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfdiagnostics QoIBug: Diagnostics Quality of ImplementationgenericsFeature: generic declarations and typesopaque result typesFeature → types → opaque types: opaque result typesopaque typesFeature → types: opaque typesswift 6.2type checkerArea → compiler: Semantic analysis

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions