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

Stephen Zabrecky
Stephen Zabrecky
6,298 Points

What does the compiler want for Enumerations and Optionals in Swift 3?

My code errors out when I try to return Book. When I comment it out and check my work again, it complains that I'm not returning anything.

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"], let Price = dict["price"], let PubDate = dict["pubDate"] else {
        return nil
    }
    self.title = Title
    self.author = Author
    self.price = Price
    self.pubDate = PubDate
    //return Book(title: self.title, author: self.author, price: self.price, pubDate: PubDate)
}

}

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"], let Price = dict["price"], let PubDate = dict["pubDate"] else {
            return nil
        }
        self.title = Title
        self.author = Author
        self.price = Price
        self.pubDate = PubDate
        //return Book(title: self.title, author: self.author, price: self.price, pubDate: PubDate)
    }
}

1 Answer

Daniel Santos
Daniel Santos
34,969 Points

First of all, I have to say that this got me too. Look at the declaration of the Book struct. No only pubDate is an optional string, but price is too. In your guard, you should only check for title and author and do the same things that you are doing. By the way, the ONLY thing you can return in a failable initializer is 'nil'. If you still can't get it, please don't hesitate to respond back, so I can post the answer. I just want to stimulate your brain a little bit.

Have fun!

-Dan

Stephen Zabrecky
Stephen Zabrecky
6,298 Points

Ah, so I don't make checks to non-optional values with a guard because they must contain a value right?

Daniel Santos
Daniel Santos
34,969 Points

That is correct. There is not reason to check because they must contain a value.