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 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.