Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Enumerations and Optionals in Swift Introduction to Optionals Initializing Optional Values

Matthew Ingram
PLUS
Matthew Ingram
Courses Plus Student 4,718 Points

The code passes the test but crashes Xcode

Hi. This code passed the challenge but when I created an instance with all the values then removed one of the optional values and Xcode crashed.

optionals.swift
struct Book {
    let title: String
    let author: String
    let price: String?
    let pubDate: String?
    init?(dict: [String : String]) {

        guard let title = dict["title"], let author = dict["author"] else {
            return nil
        }
        let price = dict["price"]
        let pubDate = dict["pubDate"]

        self.author = author
        self.title = title
        self.pubDate = pubDate
        self.price = price
    }
}

2 Answers

Arman Arutyunov
Arman Arutyunov
21,900 Points

What do you mean you removed one of the optional values? If you remove let's say let price: String? line you have to remove self.price = price line as well and nothing will crash. Or you're talking about something different?

Matthew Ingram
PLUS
Matthew Ingram
Courses Plus Student 4,718 Points

Like if an instance in Xcode and I take out “pubDate” : “2014” or “price” : “10:99” Xcode crashes.