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

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

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?

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