我正在編寫一個應用程序來顯示和瀏覽一系列使用Swift的問題和答案。我目前有一個問題詞典和相關答案,然後我通過使用.map創建一個'flashcard'對象(每個對象都有一個問題,它是相關的答案)。爲什麼我的數組不是從第一個映射到它的項開始的? Swift
當我然後從數組中訪問這些對象時,出於某種原因,返回的第0項似乎是我的字典中的第二項,而不是第一項(例如'問題2')。有人可以解釋爲什麼這是嗎?這是其產生數據的排列,並提供給項返回到相關的視圖控制器的裝置的類:
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]
}
}
然後,這是我的視圖控制器,其中我請求的對象被顯示:
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
}
}
}
當我運行應用程序時,顯示的第一個問題是「問題2」,當我期待它成爲「問題1」...?
相關:[有序字典在Swift](http://stackoverflow.com/questions/30969688/ordered-dictionary-in-swift)。 –