traversing a class with For Each...In

I’m trying to traverse a class (that contains an Integer() array) with:

For Each i As Integer in iTraverse System.DebugLog("element:"+Str(i)) Next

I tried

Function Operator_Convert() As Integer() return integerList End Function

but I always get the error: “This is not an array but you are using it as one”

(of course I can expose integerList but I was trying to avoid it and pretend the class behaves completely like an array)


“For Each” in Xojo is just focused on Arrays.

To inspect objects you must use Introspection:

Check GetTypeInfo() and TypeInfo Class

As far as I know, “for each” only works with arrays.
But with a class, you can use operator_subscript to implement an indexed lookup from you class, but you would need to do something like
(assuming the integer array is called items() as integer

Function operator_subscript(index as integer) As integer Return items(index) End Function
Then you can loop through the items…

dim i as integer for i=0 to iTraverse.ubound System.DebugLog("element:"+Str(iTraverse(i))) next
while also adding a ubound function to the class

Function ubound() As integer Return UBound(items) End Function

On the other hand, you could also access the array directly with

For each i as integer in iTraverse.Items()

(I suspect that was what you were trying to do to begin with)

iTraverse is the class ?
I’m fairly confident that the operator_convert isn’t being invoked
You’d need to do one of two things (neither of which is ideal)

  1. For Each i As Integer in iTraverse.Operator_Convert System.DebugLog("element:"+Str(i)) Next
  2. dim ints() as integer = Itraverse For Each i As Integer in ints System.DebugLog("element:"+Str(i)) Next
    both of these negate the intent of what you were trying to write

If the intent is just accessing an array of ints in a object, why not directly? Like in this simulation:

Class Window1
Inherits Window

//Window1 Control PushButton1:

Sub Action()
  Dim it As iTraverse = New iTraverse // Obj with array it.myInts full of ints
  Dim s As String
  For each i As Integer in it.myInts // my array of ints in my iTraverse Object
    s=s+Str(i)+" "
End Sub

End Class

Class iTraverse

Sub Constructor()
End Sub

Private Sub randomInts()
  Dim r As New Random // randomizer
  Dim top As Integer = r.InRange(10, 15) -1 // Random define capacity from 10 to 15 items
  Redim self.myInts(top) // random resize the array of ints to 10 to 15 items (zero based)
  For i As Integer = 0 to top
    self.myInts(i) = r.InRange(111,999) // Fill the Array with random numbers 
End Sub

//Property iTraverse.myInts()
myInts() As Integer

End Class

yes, I think the easy solution is just to use the internal array.

For Each i As Integer in iTraverse.integerArray

I was curious if to have a class that behaves like an array (in all its facets) was possible but I see this part is not possible.