如何修复错误:没有“前缀”候选者产生预期的上下文结果类型“[String]”?

问题描述 投票:0回答:2

我正在尝试跨不同文件访问变量,基本上是在

ContentView
和子视图之间。
我在我的
@State private var
中创建了一个
ContentView
,并在我的子视图中创建了
@Binding var

我有一本
[String: Int]
类型的字典,我正在尝试计算 PDF 中单词的频率。 当我对字典中的项目进行排序并使用前缀获取前 5 个项目时,我希望更新 var,以便我可以通过内容视图在应用程序本身中显示它。

错误产生于

topFive = mostFrequent.prefix(5)

我认为问题是我说的是 [String] 类型,我可能需要做其他事情,但我不确定。为了清晰地布局,该应用程序将按频率对 PDF 中的单词进行排序,并将其显示在应用程序中。我只需在控制台中打印单词就可以做到这一点,但我的问题是在应用程序本身中显示它。

struct ContentView: View { 
    @State private var documentUrl: URL?
    @State private var topFive: [String] = []
             
    var body: Some View { 
        EmptyView().sheet(item: $documentUrl { url in PDFComponent(topFive:$topFive, url: url) 
            SheetView()
        }
    }

    struct PDFComponent: UIViewRepresentable { 
        @Binding var topFive: [String]
        let documentContent = NSMutableAttributedString()
        func updateView(_ uiView: PDFView, context: Context) { 
            enumerate(in: docSubstance.string) { 
                topFive = mostFrequent.prefix(5)
            }
        }
    }
}
swift dictionary swiftui mac-catalyst
2个回答
4
投票

您在 topFive 中获取了一个子字符串数组,请尝试使用它来获取一个字符串数组:

topFive = mostFrequent.prefix(5).map{String($0)}

0
投票

就像之前的答案所说,这是因为结果类型是ArraySlice

另一种方法

topFive = Array(mostFrequent.prefix(5))
© www.soinside.com 2019 - 2024. All rights reserved.