-1

I did implement class which use subscript and return objects like following:

class PlacesSet {
  ...
  subscript(i: Int) -> Place {
      get {
          return stored[i];
      }
      set {
          stored[i] = newValue;
      }
  }
}

But when I try to pass it as array in some cocoa function it returns error. Should I implement some protocol and missing methods? And is it possible to do in general?

famer
  • 469
  • 1
  • 5
  • 14
  • Which error? runtime or compilation? Post an example of code that fails – Antonio Oct 24 '14 at 15:32
  • it says that PlacesSet not type of NSArray and if I add :NSArray to that I'm getting "overriding indexed subscript with incompatible type (Int) -> Place" – famer Oct 24 '14 at 15:34

1 Answers1

0

Implementing a subscript doesn't magically turn a class or struct into an array, so you can't pass an instance of PlaceSet where a swift array or NSArray is expected.

What you can do is implement a method in your class that returns an NSArray:

func toArray() -> NSArray {
    ...
}

or a property if you prefer:

var asArray: NSArray { return ... }

If you really want your class to behave like an NSArray, then make PlaceSet a subclass of it - but it's something that I don't recommend. The same cannot be done with a swift array, because it's a struct, hence it doesn't support inheritance.

Antonio
  • 71,651
  • 11
  • 148
  • 165
  • it may work but, when I add confirm class to protocol NSArray and whether implement asArray or not error is still there "overriding indexed subscript with incompatible type (Int) -> Place" So i can't use asArray with subscript so far, but in need of both behaviors – famer Oct 24 '14 at 15:56
  • Sorry it's not clear what you mean - pls post the code where the error happens, without that it's impossible to figure out what's wrong in your code – Antonio Oct 24 '14 at 15:58
  • if i do thing like: "mapKitView.addAnnotations(navigation.places)" error that it's not subtype of NSArray, even with asArray var but if i add :NSArray to class. error is "overriding indexed subscript with incompatible type (Int) -> Place" on subscript line – famer Oct 24 '14 at 16:14
  • That doesn't help much, because I don't know what `navigation.places` is – Antonio Oct 24 '14 at 16:20