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 Generics in Swift Generic Types Creating a Generic Type

Christopher Jr Riley
Christopher Jr Riley
35,874 Points

The code I wrote in the challenge was only considered correct because I changed 'let' to 'var'. Why?

In the code challenge, it asks to add a dequeue method that removes the first element of the array and returns said element. I typed it up in Xcode playgrounds and it didn't complain. The code you see below is what I wrote up:

struct Queue<Element> {
    var array: [Element] = []

    var isEmpty: Bool {
        if array.count == 0 {
            return true
        } else {
            return false
        }
    }

    var count: Int {
        return array.count
    }

    mutating func enqueue(_ value: Element) {
        array.append(value)
    }

    mutating func dequeue() -> Element? {
        if array.count == 0 {
            return nil
        }

        let valueToRemove = array.first
        array.remove(at: 0)

        return valueToRemove
    }
}

However, this was considered as incorrect and gave me this reason:

"The stored property needs to be declared as a variable and not a constant"

The only thing that's not a variable is on line 25, shown below:

let valueToRemove = array.first

I changed it to var...

var valueToRemove = array.first

... and, in spite the fact that Xcode playgrounds is telling me to consider changing it back to "let", the code was considered as correct.

I don't understand why this is the case, as it shouldn't matter either way. Why is it now correct, but the previous attempt wasn't?

For reference, here's the code that the Code Challenge considered as correct:

struct Queue<Element> {
    var array: [Element] = []

    var isEmpty: Bool {
        if array.count == 0 {
            return true
        } else {
            return false
        }
    }

    var count: Int {
        return array.count
    }

    mutating func enqueue(_ value: Element) {
        array.append(value)
    }

    mutating func dequeue() -> Element? {
        if array.count == 0 {
            return nil
        }

        var valueToRemove = array.first
        array.remove(at: 0)

        return valueToRemove
    }
}