swift 如何修复错误:没有'prefix'候选项产生预期的上下文结果类型'[String]'?

ztyzrc3y  于 5个月前  发布在  Swift
关注(0)|答案(2)|浏览(51)

我试图在不同的文件中访问一个变量,基本上是在ContentView和一个子视图之间。
我在ContentView中创建了一个@State private var,在子视图中创建了一个@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)
            }
        }
    }
}

字符串

uxhixvfz

uxhixvfz1#

如果你在topFive中得到一个子字符串数组,尝试使用这个来得到一个字符串数组:

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

字符串

z2acfund

z2acfund2#

就像前面的答案所说的那样,这是因为如果ArraySlice
另一种方法

topFive = Array(mostFrequent.prefix(5))

字符串

相关问题