如何在Swift中随机化JSON中的数据?

flseospp  于 2023-06-25  发布在  Swift
关注(0)|答案(1)|浏览(113)

我的目标是为情侣编写一个应用程序,这样他们就可以互相提问了。我卡住了因为我似乎不能随机化数据。
我希望每次点击按钮时数据都是随机的。

以下是我的JSON数据:

[
    {
        "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?"
    }
]

这是我的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)")
        }
    }
}

以下是错误显示的代码:

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()
        }
        
       
    }
}

以下是我无法随机化问题时的错误:

正如我说的,我的目标是创建按钮,每次我点击它,问题都会改变。

qco9c6ql

qco9c6ql1#

这一行不正确:

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

这恰好解码了一个QuestionJSON。你有一个数组,所以你的意思是:

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

相关问题