This is the struct of my array:
struct Question {
let imgName: String
let questionText: String
let options: [String]
let correctAns: Int
var wrongAns: Int
var isAnswered: Bool
}
var questionsArray = [Question]()
Here is how the array is populated currently:
let que1 = Question(imgName: "img1", questionText: "What is 2 x 2 ?", options: ["2", "4", "8", "6"], correctAns: 1, wrongAns: -1, isAnswered: false)
let que2 = Question(imgName: "img2", questionText: "What is 4 + 2 ?", options: ["9", "4", "3", "6"], correctAns: 3, wrongAns: -1, isAnswered: false)
questionsArray = [que1, que2]
I would like to put data in a text file and populate my questionsArray. So I created a file, data.txt and put it into bundle. Below is the content of data.txt. Each question is separated by a new line.
Question(imgName: "img1", questionText: "What is 2 x 2 ?", options: ["2", "4", "8", "6"], correctAns: 1, wrongAns: -1, isAnswered: false)
Question(imgName: "img2", questionText: "What is 4 + 2 ?", options: ["9", "4", "3", "6"], correctAns: 3, wrongAns: -1, isAnswered: false)
I tried to use this method:
var arrayOfStrings: [String]?
do {
if let path = Bundle.main.path(forResource: "data", ofType: "txt") {
let data = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
arrayOfStrings = data.components(separatedBy: "\n")
questionsArray = arrayOfStrings
}
} catch let err as NSError {
print(err)
}
However, I received an error, Cannot assign value of type '[String]?' to type '[Question]' for the line questionsArray = arrayOfStrings.
How to solve this?
arrayOfStringis[String]andquestionsArrayis[Question]. The types clearly don't match. That's what the error message says. How are the single lines organized to separate the fields? I highly recommend to save the data as JSON or Property List and decode it directly into the struct.questionsArray.