我嘗試從 txt 檔案中提取一些單詞,但我無法管理它。這是我的代碼:
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)
}
}
我有一個錯誤Text(allWords.count)告訴我“在呼叫初始化程式時沒有完全匹配”如果我替換allWords.count例如allWords\[0\]我有一個致命錯誤告訴我“索引超出范圍”
我真的不明白發生了什么
我已經嘗試過其他功能,但我總是有類似的錯誤
我只想擁有例如第二個元素
預先感謝您的幫助
uj5u.com熱心網友回復:
作為 Swift/SwiftUI 的許多超級模糊的錯誤訊息之一,對初始化程式的呼叫中沒有完全匹配幾乎總是意味著錯誤是由于型別不匹配/錯誤的型別被用作給定函式的輸入。在您的情況下,您正在嘗試使用帶有視圖的Int(由.count方法回傳),該Text()視圖以 aString作為引數。
一些可能的解決方案:
Text(String(allWords.count))Text("\(allWords.count)")(歸功于@Paulw11 的評論)Text(allWords.count.description)(歸功于@lorem ipsum 的評論)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/449310.html
