Swift合并。从超时处理程序块到 return 的正确方法是什么?

Swift Combine. What is a correct way to return from a block of a timeout handler?

我需要在 Combine 中实现超时函数的处理程序。让我们考虑以下代码结构:

SomeKindOfPublisher<Bool, Never>()
   .timeout(timeoutInterval, scheduler: backgroundQueue,
      customError: { [weak self] () -> Never in
         ...
         while true {} // This block should not return because of Never
      }

我的问题是如何避免奇怪的行while true {}?我不想将 Never 更改为 Error 类型。

不确定这是否是您想要的,但我发现在没有失败的情况下处理发布者超时的最佳方法 (Failure == Never) 是强制特定错误类型并在完成时处理超时错误。

enum SomeKindOfPublisherError: Error {
    case timeout
}

publisher
    .setFailureType(to: SomeKindOfPublisherError.self)
    .timeout(1, scheduler: backgroundQueue, customError: { .timeout })
    .sink(receiveCompletion: {
        switch [=10=] {
        case .failure(let error):
            // error is SomeKindOfPublisherError.timeout if timeout error occurs
            print("failure: \(error)")
        case .finished:
            print("finished")
        }
    }, receiveValue: { print([=10=]) })

如果认为超时运算符不自行将发布者故障类型更改为自定义错误很奇怪,但这是我发现的某种解决方法。