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

Jeff McDivitt
Jeff McDivitt
23,970 Points

Generics Swift 3 - Task 5 of 5

Cannot get the last part of this challenge to pass

generics.swift
struct Queue<Element> {
    //Task 1
    var array: [Element] = []

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

    var count: Int {
        return array.count
    }

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

    public mutating func dequeue() -> Element? {
        guard array.isEmpty, let element = array.first else { return nil }

        return element
    }
}
Robert Berry
seal-mask
.a{fill-rule:evenodd;}techdegree
Robert Berry
iOS Development with Swift Techdegree Student 10,893 Points

I struggled with this last challenge as well. Here is a solution I just found in the forums that worked.

mutating func dequeue() -> Element? {
        if self.array.isEmpty == false {
            return self.array.remove(at: 0)
        } else {
            return nil
        }
    }

1 Answer

Jeff McDivitt
Jeff McDivitt
23,970 Points

Thanks Robert I figured it out with the below

  public mutating func dequeue() -> Element? {
        guard array.isEmpty, let element = array.first else { return nil }

        array.remove(at: 0)

        return element
    }