2

I'm trying to create a simple Swift extension containing a calculated property. I don't understand why I'm getting this compile error (“declaration only valid at file scope”). The error is at the beginning of the "private extension OpStack" line. (This code is contained in a class.)

If I remove all of the code inside the extension, I still get the same error.

Here's the code:

private typealias OpStack = Array<Op>

  private extension OpStack {
//^ error:"This declaration is only valid at file scope"
    var topIsOperation: Bool {
      if self.isEmpty { return false }
      switch self[self.count-1] {
        case .Operand:
          return false
        default:
          return true
      }
    }
  }

1 Answers1

1

The problem is extension Array<> { } works, extending Arrays, but extension Array<SomeType> { } does not work because its trying to extend some particular arrays with elements of type SomeType instead of all arrays.

I solved the problem by using a struct instead of trying to extend Array:

struct OpStack {
  var ops = [Op]()
  var topIsOperation: Bool {
      if self.ops.isEmpty { return false }
      switch self.ops[self.ops.count-1] {
        case .Operand:
          return false
        default:
          return true
      }
  }
}

Alternatively, I could have created a function:

func topIsOperation(a: [op]) -> bool { }