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

Jun Kakeno
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jun Kakeno
iOS Development with Swift Techdegree Graduate 24,842 Points

Creating a generic type 5/5

I've tried this on the playground and it works. I'm not sure why it doesn't pass the challenge. Please help.

generics.swift
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(_ element: Element) {
      array.append(element)
  } 

  mutating func dequeue()->Element?{
      if array.count != 0{
        var first = array[0]
        array.remove(at: first as! Int)
        return first
      }
      return nil
  }
}

2 Answers

Hi Jun, here are some things to change:

  1. Remember that we already created the computed property 'isEmpty' so use that instead in 'dequeue'.
  2. Also it states that 'first' should be an optional. So technically you only need one return since it will either be nil or not, no need for a nil return.
  3. You can use array[0] or array.first.
  4. You can use array.remove(at: 0) or array.removeFirst()
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(_ element: Element) {
        array.append(element)
    }

    mutating func dequeue() -> Element? {
        var first: Element?
        if isEmpty == false {
            first = array.first
            array.removeFirst()
        }
        return first
    }
}

Your welcome and if it worked please remember to upvote and mark me best answer.