skip to Main Content

My goal is to code an app for couples so they can ask questions to each other. I’m stuck because I can’t seem to randomize the data.

I want the data to be randomize every time I click the button.

Here is my JSON data:

[
    {
        "questionNumber": 0,
        "question": "Do you have any dreams of achieving something together in the future?"
    },
    {
        "questionNumber": 1,
        "question": "How do you handle stress and difficulties as a couple?"
    },
    {
        "questionNumber": 2,
        "question": "What is your favorite shared travel memory?"
    }
]

Here is my JSONManager:

import Foundation


struct QuestionJSON: Codable {
    
    var questionNumber: Int
    var question: String
    
}

extension Bundle {
    func decode<T: Decodable>(_ type: T.Type, from file: String, dateDecodingStrategy: JSONDecoder.DateDecodingStrategy = .deferredToDate, keyDecodingStrategy: JSONDecoder.KeyDecodingStrategy = .useDefaultKeys) -> T {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError("Failed to locate (file) in bundle.")
        }

        guard let data = try? Data(contentsOf: url) else {
            fatalError("Failed to load (file) from bundle.")
        }

        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = dateDecodingStrategy
        decoder.keyDecodingStrategy = keyDecodingStrategy

        do {
            return try decoder.decode(T.self, from: data)
        } catch DecodingError.keyNotFound(let key, let context) {
            fatalError("Failed to decode (file) from bundle due to missing key '(key.stringValue)' not found – (context.debugDescription)")
        } catch DecodingError.typeMismatch(_, let context) {
            fatalError("Failed to decode (file) from bundle due to type mismatch – (context.debugDescription)")
        } catch DecodingError.valueNotFound(let type, let context) {
            fatalError("Failed to decode (file) from bundle due to missing (type) value – (context.debugDescription)")
        } catch DecodingError.dataCorrupted(_) {
            fatalError("Failed to decode (file) from bundle because it appears to be invalid JSON")
        } catch {
            fatalError("Failed to decode (file) from bundle: (error.localizedDescription)")
        }
    }
}

Here is the code where the error shows up:

struct test : View {
    @State private var question : QuestionJSON?
    
    var body: some View {

        VStack {
            if let question = question {
                VStack {
                    Text(String(question.questionNumber))
                        .font(.system(.title3))
                        .foregroundColor(.white)

                }.frame(width: 240)
                .background(RoundedRectangle(cornerRadius: 7.0).fill(Color.blue))
            }
        }.onAppear {
            let questions = Bundle.main.decode(QuestionJSON.self, from: "data.json")
            question = questions.randomElement()
        }
        
       
    }
}

Here is error when I can’t randomize my questions:

Here is error, when I can't randomize my questions

As I said, my goal is to create the button and every time I click it, the question changes.

2

Answers


  1. Chosen as BEST ANSWER

    i forgot to put QuestionJSON in those brackets []


  2. This line is incorrect:

    let questions = Bundle.main.decode(QuestionJSON.self, from: "data.json")
    

    This decodes exactly one QuestionJSON. You have an array of them, so you meant:

    let questions = Bundle.main.decode([QuestionJSON].self, from: "data.json")
                                       ^^^^^^^^^^^^^^
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search