如何修复错误:No ‘prefix’ candidates produce the expected contextual result type ‘[String]’
问题根源
类型不匹配是报错的核心原因:
- 你用来统计词频的
mostFrequent是[String: Int]类型的字典,排序后得到的是元素为(key: String, value: Int)的结构体数组 - 调用
prefix(5)后返回的是该数组的切片类型Slice<[(key: String, value: Int)]>,和你声明的[String]类型的topFive不兼容,无法直接赋值
解决方法
根据你的展示需求二选一即可:
- 仅需要展示前5的单词:提取切片中所有元素的key,转为标准
[String]数组后赋值topFive = mostFrequent.prefix(5).map(\.key) - 需要同时展示单词和对应词频:修改
topFive的类型声明,赋值时将切片转为标准数组即可// ContentView中修改声明 @State private var topFive: [(word: String, count: Int)] = [] // PDFComponent中赋值 topFive = Array(mostFrequent.prefix(5))
其余代码语法问题修正
你提供的代码中还存在几处语法错误,同步修正如下:
import SwiftUI import PDFKit struct ContentView: View { @State private var documentUrl: URL? // 仅展示单词就保留[String],需要词频就改成上面的[(word: String, count: Int)] @State private var topFive: [String] = [] var body: some View { EmptyView() .sheet(item: $documentUrl) { url in PDFComponent(topFive: $topFive, url: url) } } struct PDFComponent: UIViewRepresentable { @Binding var topFive: [String] let url: URL func makeUIView(context: Context) -> PDFView { let pdfView = PDFView() pdfView.document = PDFDocument(url: url) return pdfView } func updateUIView(_ uiView: PDFView, context: Context) { guard let docSubstance = uiView.document?.string else { return } // 此处替换为你自己的词频统计逻辑得到mostFrequent let mostFrequent = 你的词频统计方法(docSubstance) .sorted { $0.value > $1.value } topFive = mostFrequent.prefix(5).map(\.key) } } }
内容的提问来源于stack exchange,提问作者happycoder523
相关产品推荐
相关产品推荐

