我遇到了致命錯誤()的問題。我嘗試添加到單詞串列中,但在這一行中存在問題:
ContentView.swift 中的致命錯誤
我不知道為什么會發生這種情況我的代碼是完全正確的。此錯誤的代碼:
// id were are * here* then there was a problem - trigger a cradh and report the error
fatalError("could not load start.txt from bundle.")
整個代碼是;
import SwiftUI
struct ContentView: View {
@State private var usedWords = [String]()
@State private var rootWord = ""
@State private var newWord = ""
var body: some View {
NavigationView {
List {
Section {
TextField("enter your word", text: $newWord)
.textInputAutocapitalization(.never)
}
Section {
ForEach(usedWords, id: \.self) { word in
HStack {
Image(systemName: "\(word.count).circle")
Text(word)
}
}
}
}
.navigationTitle(rootWord)
.onSubmit(addNewWord)
.onAppear(perform: startGame)
}
}
func addNewWord() {
// lowercase and trim the word, to make sure we don:t add duplicate words with case differences
let answer = newWord.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
// exit if the remaining string is empty
guard answer.count > 0 else { return }
// extra validation to come
withAnimation {
usedWords.insert(answer, at: 0)
}
newWord = ""
}
func startGame() {
// 1.find the URL for start.txt in our app bundle
if let startWordsURL = Bundle.main.url(forResource: "start",withExtension: "txt") {
// 2.load start.txt into a string
if let startWords = try? String(contentsOf: startWordsURL) {
// 3.split the string up into an array of strings, splitting on line breaks
let allWords = startWords.components(separatedBy: "\n")
// 4.pcik one random word, or use "yamori" as a sensible default
rootWord = allWords.randomElement() ?? "yamori"
// if we are here everything has worked, so. we can exit
return
}
}
// id were are * here* then there was a problem - trigger a cradh and report the error
fatalError("could not load start.txt from bundle.")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
任何想法?如何修復該錯誤
謝謝。
uj5u.com熱心網友回復:
此失敗的原因是“start.txt”的 url 為 nil 或try? String(contentsOf: startWordsURL)失敗。為了幫助您除錯并理解為什么您當前的代碼設計不好,請考慮以下設計:
func startGame() {
// 1.find the URL for start.txt in our app bundle
guard let startWordsURL = Bundle.main.url(forResource: "start",withExtension: "txt") else{
//assign the default value
rootWord = "yamori"
// if the url is not found this will print in the console
print("File could not be found")
return
}
do{
// 2.load start.txt into a string
let startWords = try String(contentsOf: startWordsURL)
// 3.split the string up into an array of strings, splitting on line breaks
let allWords = startWords.components(separatedBy: "\n")
// 4.pick one random word, or use "yamori" as a sensible default
rootWord = allWords.randomElement() ?? "yamori"
} catch{
//if the file couldn′t be read this will print the error in the console
print(error)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497952.html
上一篇:am-pm格式的日期選擇器
