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

Options task Help

Hey all, thanks for the help.

I am getting a compile error telling me that pattern of type 'String" cannot match type 'String?' in my guard statement

Any help would be greatly appreciated.

optionals.swift
struct Book {
    let title: String
    let author: String
    let price: String?
    let pubDate: String?

    init?(dict: [String: String]){
        guard let self.title = dict["title"], let self.author = dict["author"] else {
            return nil
        }

        self.price = dict["price"]
        self.pubDate = dict["pubDate"]

    }

}

2 Answers

When you use self in your guard let you are trying to create the constant all over again. You want to create a new constant and then assign the original constant that value.

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
        }

        self.title = title
        self.author = author
        self.price = dict["price"]
        self.pubDate = dict["pubDate"]
    }
}

I guess an easier way for you to understand what is happening is to see it with the guard let names changed.

    init?(dict: [String: String]){
        guard let bookTitle = dict["title"], let bookAuthor = dict["author"] else {
            return nil
        }

        self.title = bookTitle
        self.author = bookAuthor
        self.price = dict["price"]
        self.pubDate = dict["pubDate"]
    }

Hi Brandon, Thank you...

I literally, just re-wrote in Xcode realizing that with guard let, I was re-creating the constant as you stated.

Appreciate the response