I try to extract some words from a txt file but I can't manage it. This is my code :
import SwiftUI
struct ContentView: View {
@State private var allWords : [String] = []
func startGame() {
if let startWordsURL = Bundle.main.url(forResource: "start", withExtension: "txt") {
if let startWords = try? String(contentsOf: startWordsURL) {
allWords = startWords.components(separatedBy: "\n")
return
}
}
if allWords.isEmpty {
allWords = ["silkworm"]
}
fatalError("Could not load start.txt from bundle.")
}
var body: some View {
VStack{
Text(allWords.count)
.onAppear(perform: startGame)
.font(.system(size: 30))
.frame(width: 1000, height: 75)
.background(Rectangle()
.foregroundColor(.white))
.border(Color.black, width: 1)
}
}
I have an error on the line Text(allWords.count)
which tell me "No exact matches in call to initializer"
And If I replace the allWords.count
by for example allWords\[0\]
I have a fatal error which tell me "Index out of range"
I don't really understand what happen
I have already tried other functions but I always have similar errors
I just want to have for example the second element
Thank you in advance for your help
CodePudding user response:
As one of Swift/SwiftUI's many super-vague error messages, No exact matches in call to initializer almost always means that the error is due to the types mismatching / the wrong type being used as input for a given function. In your case, you are trying using an Int
(returned by the .count
method) with a Text()
view, which takes a String
as a parameter.
Some possible solutions:
Text(String(allWords.count))
Text("\(allWords.count)")
(credit to @Paulw11's comment)Text(allWords.count.description)
(credit to @lorem ipsum's comment)