我搜索了多个类型,因此通用搜索方法有一个通用类型T,多个简单方法根据需要调用它指定类型.我想推迟搜索方法的开始(Combine中为debounce),并且我想尽可能深地隐藏此代码.

我通常在我的项目中使用Deliverc/await API,只有在必要时才使用Combine.我没有使用Deliverc/await找到内置解决方案,所以我要使用Combine的debounce.(请告诉我是否有不带Combine的更Clean 解决方案)

所以我必须从adminc/wait到Combine然后返回.这需要使用withCheckedContinuation,这会丢失T并导致错误:

// simple generic specification using Event
func searchEvents(query: String) async -> [Event] {
    await search(query: query)
}

// simple generic specification using Artist
func searchArtists(query: String) async -> [Artist] {
    await search(query: query)
}

// debouncing layer between specifications and generic search
private func search<T>(query: String) async -> [T] where T: Codable, T: Identifiable  {
    await withCheckedContinuation { continuation in
        Debouncer().debounce(query) { query in
            Task {
                // Generic parameter 'T' could not be inferred
                let a = await self.performSearch(query: query) // <- error here
                continuation.resume(returning: a)
            }
        }
    }
}

// generic search function, details don't matter
private func performSearch<T>(query: String) async -> [T] where T: Codable, T: Identifiable {
    ...
}

// class performing simple debouncing
class Debouncer {

    static var shared = Debouncer()

    private var debounceSubscription: AnyCancellable?

    func debounce(_ string: String, block: (String) -> ()) {
        debounceSubscription?.cancel()
        debounceSubscription = Just(string)
            .debounce(for: .milliseconds(200), scheduler: DispatchQueue.global(qos: .background))
            .sink { string in
                block(string)
            }
    }
}

有没有一种优雅的方法可以让它自动理解类型,而无需将其作为参数传递(类型:T.类型,查询:字符串)?

推荐答案

告诉编译器performSearch将返回T数组

let a: [T] = await performSearch(query: query)

现在performSearch中的T将与search中的T相同,编译器可以推断出它是什么类型.

Swift相关问答推荐

在运行时检测蒸汽工人的类型

依赖于@Environment的init@StateObject

如何在DATE()中进行比较

';NSInternal不一致异常';,原因:';可见导航栏Xcode 15.0 Crash请求布局

本地对象的异步/等待引用捕获总是安全的还是理论上不安全?

我如何读取并通知可可 macos 中某个类的计算(computed)属性?

从 iPhone 中的安全飞地获取真正的随机数?

TextField 键入未完成

使用 WrappingHStack 文本溢出到新行

swift 是否遇到 Java 的 2gb 最大序列化大小问题?

将 struct 作为泛型类型传递并访问该泛型类型属性

类型 '()' 不能符合 View (除非它肯定是 View,这次没有恶作剧)

Swift Components.Url 返回错误的 URL

阻止其他类型的键盘

Vapor - 流利的,将对象保存到 PostgreSQL

FirebaseStorage:如何删除目录

SwiftUI 中的 .primary 和 .secondary colored颜色 是什么?

获取设备图像比例(例如@1x、@2x 和@3x)

将活动指示器 colored颜色 更改为黑色

使用相机进行人脸检测