This blog post was originally written by Javier Menendez in 2017 and has been updated for Xojo API 2.0 by Wayne Golding.
In programming, iterators are the mechanisms that run through all the items of a collection without needing to know in advance how many items compose that collection. To do this in Xojo, use the commands For Each… Next
. What are the main differences when comparing For Each… Next
with the conventional For… Next
?
The first difference is that with For Each… Next
we can’t assume that we are iterating the items in the collection in order, as is the case when using the variable of the conventional For… Next
. The second difference is that the iterator will be invalid when the iterated elements are modified or when we modify the number of elements in the collection during the iteration process.
By default in Xojo, there are a couple of collections that are iterable: Arrays, Dictionaries and FolderItem.Children. Wouldn’t it be great to extend this behaviour to other classes, making them more flexible? The key to doing just that is in two of Xojo’s Class Interfaces: Iterator and Iterable.
Download the example project used in this tutorial.
Using Iterator
In order to implement this behaviour in our classes so they can use the For Each… Next
schema, the real work is in the Iterator Class Interface. Under this interface, we can find the definition of the methods that are needed to implement the class and that are responsible for advancing every item of the collection, and for returning the current value of the collection:
- MoveNext. Moves to the next element of the Collection, returning
True
if it has not reached the end of the collection,False
when reached past the last element in the Collection. - Value This is the Class Interface method that returns the current element of the collection as an Variant data type.
From this, it is easy to conclude that our iterable classes need to implement a counter (as a Property) that updates its value for every MoveNext
invocation. We will also use this property to check if it has reached the maximum number of elements. Also, be aware that the property has to be initialized using the value -1 (that is, as an invalid value), as it is stated in the documentation that we have to invoke MoveNext
before we can get the first iterable element from the collection.
On the other hand, we will handle all the error cases during the iteration process raising IteratorException
.
In order to see all this in action, let’s run through an example using the Person
class in charge to store in their instances all the possible postal addresses associated with a person.
Let’s start defining ourPerson
class as a simple set of Properties:
- firstName As String
- middleName As String
- secondName As String
Also, add the Property in charge of referencing all the postal addresses assigned to the Person, using an Array:
- postalAddresses() As PostalAdress
With that, we have finished our Person class definition. It’s very simple but works for the purpose of this example.
We will also create a simple (and incomplete) definition for the PostalAddress class using a set of public properties so they serve the purpose of the main topic.
- street As Text
- streetNumber As Integer
- streetFlat As Integer
Creating an Iterator
Once we have the two classes needed for our example (Person and PostalAddress), we can define the Class responsible for acting as the iterator; that is, returning every element from the collection for the associated class. In this example we will return every object of the PostalAddress that is associated with an instance of the Person class. In fact, the Iterator is responsible of doing all the hard work, moving forward the counter to the next item, and returning the object or value when requested.
Let’s create a new Class with the namePersonIterator
. In this case, use the associated Inspector to select theChoose
button next to theInterfaces
label. This will display a window containing all the available Class Interfaces. Select the checkbox forIterator
and confirm the selection.
The IDE will now add the following defined methods for the selected class interface:
- MoveNext. The documentation states that this is the method invoked before calling the Value method in order to get a new value. In fact, in the method implementation we have to write the code that increases the counter value, and also checks if the counter value is over the available quantity of items. Meaning, we have to add a
counter
Property to our class, and initialize it with the value -1. - Value. This is the method that will be called every time we need to get a new value. In our example, this will return a new PostalAddress object from the available items.
Thus, the implementation for theMoveNext
method could be the following:
counter = counter + 1
But the method signature and the class interface documentation states that the method has to return a boolean value ofTrue
if there are remaining available items to iterate andFalse
if the quantity of iterable items has been surpassed. In the case we should raise an exception in order to point this out.
For example, our class could check if the counter doesn’t exceed the quantity of items stored by the PostalAddresses Array, returning the corresponding boolean value.
But let’s fill in some holes before writing the final implementation for theMoveNext
method. First, let’s add some more needed properties:
- maxPostalAddresses As Integer. This will be responsible for storing the number of elements available under the PostalAddress Array.
- source As Person. This will be in charge of saving the reference to the Person object it has to iterate.
- The Calculated Property valid as Boolean. We will use the
Get
method from this calculated property to know if the PostalAddress Array has been modified during the iteration of the object, returningFalse
when this is the case. In fact, this is the code for theGet
method:
Return if(source.postalAddresses.LastIndex = maxPostalAddresses, True, false)
Next, we will add theConstructor
method to the class using this signature:
Constructor( value As Person )
and the following code for the method:
source = value maxPostalAddresses = value.postalAddresses.LastIndex
This initialized the previously declared property’s values with the reference to the Person object that we will use to iterate over, and the number of elements included in the Array when we initialize the class. Thus, the number of original items that we will use to check if it has been modified during the iteration process.
Now we can move back to theMoveNext
method to write the final implementation:
If valid Then counter = counter + 1 Return If(counter <= source.postalAddresses.Ubound, True, False) Else Var e As New IteratorException e.Reason = "Invalid Data" Raise e End If
Inside the method implementation we will also check if the object has been modified during the iteration, returning the corresponding value:
If valid Then Return source.postalAddresses(counter) Else Var e As New IteratorException e.Reason = "Invalid Data" Raise e End If
As you can see, the Value method will return the PostalAddress item from the Person array, using the value of the Counter property as Index.
Creating the Iterable Class
Now we have to create the iterable class itself. Add a new class to the project with the name IterablePerson
and make it a subclass from the Person class. Write this data type in theSuper
field of the Inspector Panel. In addition, this class will be the one that implements the class interface Iterable, so you have to push on theChoose
button associated with theInterfaces
label in order to select and confirm the addition of the corresponding methods. In fact, is just one method:
Iterator() As Iterator
And this is the code for that method:
Var it As New iterablePerson(Self) Return it
Now we have all the definitions we need for the subclass: we get a new IterablePerson
instance passing as a parameter the iterable object (a Person subclass). Finally, we return the iterator we got and that will be used inside theFor Each… Next
loop.
Putting It All Together
Armed with all the needed classes for our example, we can finally put it all into practice. For this, add a ListBox in the main project Window (Window1
). This is the control where we will add as many rows as there are postal addresses associated with an instance of the Person class used for the example. For this, add a button to the window with the Action event and write the following code in the resulting Code Editor:
Var p As New IterablePerson p.firstName = "Juan" p.middleName = "Sin Miedo" p.secondName = "De Nada" Var d As New PostalAddress d.street = "Juan de Urbieta" d.streetNumber = 6 d.streetFlat = 1 p.postalAddresses.Add(d) d = New PostalAddress d.street = "Mi calle bonita" d.streetNumber = 8 d.streetFlat = 3 p.postalAddresses.Add(d) d = New PostalAddress d.street = "Princesa" d.streetNumber = 5 d.streetFlat = 5 p.postalAddresses.Add(d) For Each s As PostalAddress In p Listbox1.AddRow(s.street + ", " + s.streetNumber.ToString + " Piso: " + s.streetFlat.ToString) Next
Run the project, push the button and you will see how theFor Each… Next
loop iterates every postal address associated with the Person object. This is a more concise, stylish and OOP way of doing things when compared with the classicFor… Next
loop, which requires getting the upper value (or limit) and use a variable as index to get every collection object we are interested in.
*This blog post was originally written by Javier Menendez in 2017 and has been updated for Xojo API 2.0 by Wayne Golding.
Wayne Golding has been a Xojo developer since 2005 and is a Xojo MVP. He operates the IT Company Axis Direct Ltd which primarily develops applications using Xojo that integrate with Xero www.xero.com. Wayne’s hobby is robotics where he uses Xojo to build applications for his Raspberry Pi, often implementing IoT for remote control.