有没有办法简化 Swift 组合类型?

Is there a way to simplify Swift combine types?

我有一个自定义发布器,它接受一个字符串键并在该键的数据更改时发出值。假设它被称为 MyCustomPublisher.

我有一个函数,我想在 MyCustomPublisher 的实例中使用,将值转换为不同的键,然后创建一个单独的 MyCustomPublisher 实例。这看起来像这样:

    let myInfoProvider: MyCustomPublisher = ...
    myInfoProvider.tryMap { v -> Database in
        guard let value = v else { throw "No value provided" }
        return value
    }
    .map { v in
        MyCustomPublisher(key: v)
    }
    .switchToLatest()
    .tryMap { v -> String in
        guard let value = v else {
            throw "No value found"
        }
        
        return value
    }

鉴于数据是一个字符串,我希望输出类型是AnyPublisher<String, Error>,但Swift报告的实际类型是Publishers.TryMap<Publishers.SwitchToLatest<MyCustomPublisher, Publishers.TryMap<MyCustomPublisher, MyCustomPublisher>>, String>。我怎样才能使它符合 AnyPublisher?

您只需对结果调用 eraseToAnyPublisher()