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 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.