Hello, please, can anyone help me? I have been trying to compile this code for days but I get the same error: fatal error unexpectedly found nil while unwrapping an optional value xcode. I have already read many of your answers without success, could someone explain to me why it acts like this and how to remedy it?
at the level of the for loop Thanks you so much
struct BookViewModel {
var chapters: [ChapterViewModel] = [ChapterViewModel]()
init() {
let model = Bundle.main.decode(BookModel.self, from: "Book-v1.json")
for chapter in model!.chapters {
let chapterVM = ChapterViewModel(number: chapter.number, name: chapter.name, contents : chapter.contents)
self.chapters.append(chapterVM)
}
}
}
struct ChapterViewModel {
var number: Int = 0
var name: String = ""
var contents: NSAttributedString = NSAttributedString(string: "")
var textRangeLocation: Int = 0
var textRangeLength: Int = 0
var searchedNameWithText: NSAttributedString = NSAttributedString(string: "")
init(number : Int, name: String, contents : String) {
self.name = name
self.number = number
self.contents = convertToAttibutedText(contentsInStringFormat: contents)
}
}
struct BookModel: Codable {
var name: String = ""
var chapters: [ChapterModel] = [ChapterModel]()
class ChapterModel: Codable {
var number: Int = 0
var name: String = ""
var contents: String = ""
}
}
What @robnotyou said, plus this change:
init() {
guard let model = Bundle.main.decode(BookModel.self, from: "Book-v1.json") else { print("No model") ; return }
for chapter in model.chapters { // <<-- no need to unwrap anymore
let chapterVM = ChapterViewModel(number: chapter.number, name: chapter.name, contents : chapter.contents)
self.chapters.append(chapterVM)
}
}
Could you show the json file ? Take care that a slight difference in a name (lowercase vs uppercase) between struct and json will cause decode to fail.