Cannot infer type returned by previous closure

I wrote a simple function I wanted to use in my tests, to separate test phases into closures:

func given<T>(
    _ setup: () -> T,
    when: (inout T) -> Void = { _ in },
    then: (T) -> Void
) {
    var sut = setup()
    when(&sut)
    then(sut)
}

but I realized that if the given closure is complex in some way the function won't compile:

It works if I explicitly write down the type of T in the following closures, of I I use one-line given closure. It works too if I extract the given closure in a separate variable.

Does anybody know why this happens?
Is there a way swift compiler can infer the T returned from given closure?

It will only infer if the closure is a single statement. In other cases, the compiler will simply not try. You need to explicitly provide type context somewhere, like given { _ -> [String : Int] } for example.

This used to be true universally but is currently only true with inout involved.

func given<T>(
  _ setup: () -> T,
  when: (T) -> T = { $0 },
  then: (T) -> Void
) {
  then(when(setup()))
}

@Test func gwt_one() {
  given {
    let dict = [String: Int]()
    return dict
  } when: { sut in
    var sut = sut
    sut["a"] = 10
    return sut
  } then: { sut in
    #expect(sut["a"] == 10)
  }
}