Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Issues getting data from plist with nested dictionaries

Hi, I'm a real newbie and have got stuck with issues reading data from a plist ("Questions") i constructed for a Master-Detail Quiz app. The root class and subclasses for the plist are NSDictionary, where keys list the question number and values the text as String. The plist is structured as follows: Current questions(root) with three subcategories: SubjectAreas + SubQuestions + QuestionStems. The app crashes as when loading optional it finds nil in the part of the code (see below) that attempts to assign a String from the struct to a UILabel (QuestionStemLabel). Also, I wondered what the best way to indicate True/False for each and every subquestion is. It looks like swift loads Bool data from the dictionary as Int. In advance thanks for any and all advice!

// Struct to organize the questions, subject areas etc. ///

struct questions { let questionSubject: String? let questionStem: String? let subQuestion: String?

init(questionDictionary: [String: AnyObject]) {
    questionSubject = questionDictionary["SubjectAreas"] as? String
    questionStem = questionDictionary["QuestionStems"] as? String
    subQuestion = questionDictionary["Subquestions"] as? String

}

}

////////////////////////DetailViewController///////////////

var stemLabel: AnyObject? {
    didSet {
        // Update the view.
        self.configureView()
    }
}

func configureView() {

// Loading the property list////

    if let plistPath = NSBundle.mainBundle().pathForResource("Questions", ofType: "plist"),
        let questionDictionary = NSDictionary(contentsOfFile: plistPath),
        let currentQuestionDictionary = questionDictionary["CurrentQuestions"] as? [String: AnyObject]
    {

        println(currentQuestionDictionary) /// This prints the dictionary, so it has imported

        let currentQuestion = questions(questionDictionary: currentQuestionDictionary)

    }

///// The app crashed when I tried configure view and labels, as optional returned nil ///

    if let stem: AnyObject = self.questionStem {
        if let label = self.QuestionStemLabel {
            label.text = stem.description
        }
    }
}