Fatal Error Unexpectedly Found Nil When Unwrapping An Optional Value In Xcode Fix

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 = ""
    }
}
Answered by Claude31 in 726527022

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.

You are force-unwrapping "model", using "model!"
If model is nil, this will cause the app to crash.

So the first thing to check is, is "model" set? e.g.

if let model = Bundle.main.decode(BookModel.self, from: "Book-v1.json") {
	print("got model")
} else {
	print("no model")
}

If "model" is not set, then you need to understand why this line is failing:

Bundle.main.decode(BookModel.self, from: "Book-v1.json")
Accepted Answer

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.

A big thank you to all of you. My application is compiling, now there is a problem: The content of my json file does not appear I do not know why. Here is the link of the json file.

https://drive.google.com/file/d/1qMKLNcf1fvYla21Yhh_D36FuPI-0-kj2/view?usp=drivesdk

here is the code to display the chapters but I don't know why nothing is displayed

https://drive.google.com/file/d/1BFUzbk0fQB2mLotmvGPsS1FBkZlRIzSB/view?usp=sharing

that's my ChaptersViewController

please help me

You'd better start a new thread for your new question.

It seems some keys are missing in the json.

So 2 options:

  • remove for testing:
    var textRangeLocation: Int = 0
    var textRangeLength: Int = 0
    var searchedNameWithText: NSAttributedString = NSAttributedString(string: "")
  • declare those var as optional and give a default value on decode.

Example here : https://stackoverflow.com/questions/44575293/with-jsondecoder-in-swift-4-can-missing-keys-use-a-default-value-instead-of-hav

struct Source : Codable {

    let id : String?
    let name : String?

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case name = "name"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        id = try values.decodeIfPresent(String.self, forKey: .id) ?? ""
        name = try values.decodeIfPresent(String.self, forKey: .name)
    }
}
Fatal Error Unexpectedly Found Nil When Unwrapping An Optional Value In Xcode Fix
 
 
Q