You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复错误: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:48:03