I'm in the process of writing an app to display and navigate through a series of questions and answers using Swift. I currently have a dictionary of questions and associated answers which I then work through using .map to create an array of 'flashcard' objects (each holds a question and it's associated answer).
When I then go to access these objects from the array, for some reason the 0th item returned appears to be the second item in my dictionary rather than the first (e.g. 'question 2'). Can someone explain why this is? This is the class which creates the array of data and provides the means to return items to the relevant view controller:
import Foundation
class Deck {
// Create constant to hold the deck of cards
private var cards: [Flashcard]
var bookmark: Int // Remembers which card we are on
init() {
let cardData = ["Question 1" : "Answer 1",
"Question 2" : "Answer 2",
"Question 3" : "Answer 3"]
cards = cardData.map { Flashcard(question: $0, answer: $1) }
bookmark = 0 // Start with bookmark on first item in deck
}
// Getter method to return current card
public func getCurrentCard() -> Flashcard {
print("Bookmark set to \(bookmark)")
return cards[bookmark]
}
// Getter method to return the next card in the deck
public func getNextCard() -> Flashcard {
bookmark += 1
print("Bookmark set to \(bookmark)")
return cards[bookmark]
}
// Getter method to return previous card in deck
public func getLastCard() -> Flashcard {
bookmark -= 1
print("Bookmark set to \(bookmark)")
return cards[bookmark]
}
}
Then this is my view controller where I request the objects to be displayed:
import UIKit
class QuestionController: UIViewController {
// Outlet for the 'question' label
@IBOutlet weak var questionTextView: UITextView!
// Outlet for the next button
@IBAction func nextQuestion(_ sender: UIButton) {
flashcard = deck.getNextCard()
questionTextView.text = flashcard?.question
}
// Outlet for last button
@IBAction func lastQuestion(_ sender: UIButton) {
flashcard = deck.getLastCard()
questionTextView.text = flashcard?.question
}
// variable to hold current flashcard
var flashcard: Flashcard?
let deck = Deck() // Holds deck of data
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
flashcard = deck.getCurrentCard()
questionTextView.text = flashcard?.question
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Prepare flashcard item to be passed to the answer controller before segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let answerController = segue.destination as? AnswerController {
answerController.flashcard = flashcard
}
}
}
When I run the app the first question displayed is "Question 2" when I was expecting it to be "Question 1"...?