这可能是一个愚蠢而简单的错误,但我已经有一段时间没有接触Swift 了,所以我会感谢你的帮助. 我有一个属于ListToPrint类的观察对象(ListOfWordsCounted),我将在其中保存要打印的单词.
目标是在文本框中写下一个句子,然后统计每个单词的出现次数,最后显示它.我 Select 了一个列表,因为它看起来很合适,但我没有从ForEach循环中获得任何信号.
import SwiftUI
import Foundation
class Word :Identifiable {
var id:String
var nTimes:Int = 1
init(string: String) {
self.id = string
}
func count(){self.nTimes += 1}
}
class ListToPrint : ObservableObject {
var wordsToPrint:[Word] = []
init(){}
init(sentence :String){
self.update(sentence: sentence)
}
func update(sentence :String){
let componentsOfSentence = getStrComponentsArray(str: sentence)
for comp in componentsOfSentence {
if wordsToPrint.first(where: {$0.id == comp}) != nil
{
wordsToPrint.first(where: {$0.id == comp})!.count()
} else
{
wordsToPrint.append(Word(string: comp))
}
}
}
func getStrComponentsArray(str :String) -> [String] {
return str.components(separatedBy: " ")
}
}
struct ContentView: View {
@State private var sentence = ""
@ObservedObject private var listOfWordsCounted = ListToPrint()
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
TextField("Let me count your sentence", text: $sentence)
Button("Count")
{
listOfWordsCounted.update(sentence: sentence)
print(listOfWordsCounted.wordsToPrint)
}
.foregroundColor(Color.red)
.padding()
.background(Color(red: 0, green: 0, blue: 0.5))
.clipShape(Capsule())
Button("Print")
{
for word in listOfWordsCounted.wordsToPrint {
print(word.id)
}
}
List {
// Text(" appeared " + "times")
ForEach(self.listOfWordsCounted.wordsToPrint){ word in
Text(word.id)
}
}
}
.padding()
}
}
我期待着出现一个列表,其中包含我在文本框中写下的单词.