In programming, iterators are the mechanisms that allow us to walk all the members of a collection without needing to know in advance how many of them compose such a collection; and for that we can find in Xojo the commands
For Each… Next. What are the main differences in comparison to the conventional
The first difference is that with
For Each… Next we can’t assume that we are iterating the members of the collection in order, as it is the case when using the variable of the conventional
For… Next as the Index in order to access a known member of the collection. The second difference is that the iterator will be invalid when the iterated elements are modified, or when we modify the amount of elements in the collection during the iteration process.
By default in Xojo, there are a couple of collections that are iterable: the already mentioned Arrays and also Dictionaries and FolderItem.Children. Wouldn’t it be great to extend this feature so we can add this behaviour to our own classes making them more flexible? The key to making this happen is using the two Class Interfaces already included in Xojo: Iterator and Iterable.
You can download the example project used by this tutorial from this link.
In order to implement this behaviour in our classes so they can use the
For Each… Next schema, the real work is under the Xojo.Core.Iterator Class Interface. Under this interface we can find the definition of the methods that need to implement the class and that are responsible for advancing for every item of the collection, and for returning the current value of the collection:
- MoveNext. Moves to the next element of the Collection, returning
Trueif it has not reached the end of the collection, or
Falsewhen 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 Auto data type.
From this, it is easy to conclude that our iterable classes need to implement a counter (Property) that updates its value for every
MoveNext invocation. We will also use this property to check if it has reached the maximum quantity of elements. The only thing we need to be aware of is 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 an
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 our
Person class as a simple set of Properties:
- firstName As String
- middleName As String
- secondName As String
We will add also the Property in charge of referencing all the postal addresses assigned to the Person, using an Array:
- postalAddresses() as PostalAdress
With that, we will have finished our Person class definition. It’s very simple but will work for the purpose of the 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 name
PersonIterator. In this case, use the associated Inspector to push on the
Choose button related with the
Interfaces label. As the result of the previous action, the Xojo IDE will display a window containing all the available Class Interfaces. Select the checkbox for Xojo.Core.Iterator and confirm the selection.
As result of the previous action, the IDE will add the following defined methods for the selected class interface:
- MoveNext. The documentation states that this is the method invocated before calling the
Valuemethod 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 to check if the counter value is over the available quantity of items. That is, we have to add a
counterProperty to our class, and initialice 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 the
MoveNext 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
True if there are remaining available items to iterate, and
False when we have surpassed the quantity of iterable items; and in that 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 the
MoveNext method. First, let’s add some more needed properties:
- maxPostalAddresses As Integer. This will be responsible for storing the quantity 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
Getmethod from this calculated property to know if the PostalAddress Array has been modified during the iteration of the object, returning
Falsewhen this is the case. In fact, this is the code for the
Return if(source.postalAddresses.Ubound = maxPostalAddresses, True, false)
Next, we will add the
Constructor method to the class using this signature:
Constructor( value As Person )
and the following code for the method:
source = value maxPostalAddresses = value.postalAddresses.Ubound
That is: we initialize the previously declared property’s values with the reference to the Person object that we will use to iterate over, and the quantity of elements included in the Array when we initialize the class; thus, the original items quantity that we will use to check if it has been modified during the iteration process.
Now we can move back to the
MoveNext method to write its final implementation:
If valid Then counter = counter + 1 Return If(counter <= source.postalAddresses.Ubound, True, False) Else Dim e As New Xojo.Core.IteratorException e.Reason = "Invalid Data" Raise e End If
Inside the method implementation we will check also if the object has been modified during the iteration, returning the corresponding value:
If valid Then Return source.postalAddresses(counter) Else Dim e As New Xojo.Core.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 as Index the value of the Counter property.
Creating the Iterable Class
Now we have to create the iterable class itself. For that we will add a new class to the project using
IterablePerson as its name and making it a subclass from the Person class, so we have to write this data type in the
Super field of the Inspector Panel. In addition, this class will be the one that implements the class interface Xojo.Core.Iterable, so you have to push on the
Choose button associated with the
Interfaces label in order to select and confirm the addition of the corresponding methods. In fact, is just one method:
GetIterator() As Xojo.Core.Iterator
And this is the code you have to write for that method:
Dim it As New iterablePerson(Self) Return it
With this we have all the definitions we need for the subclass: we get a new
IterablePerson instance passing as parameter the iterable object (a Person subclass). That’s all! Finally, we return the iterator we get and that will be used inside the
For 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, we will use a ListBox in the main project Window (
Window1). This is the control where we will add as many rows as postal addresses associated with a instance of the Person class used for the example. For this, add also a button to the window with the Action event and write the following code in the resulting Code Editor:
Dim p As New iterablePerson p.name = "Juan" p.middleName = "Sin Miedo" p.secondName = "De Nada" Dim d As New PostalAddress d.street = "Juan de Urbieta" d.streetNumber = 6 d.streetFlat = 1 p.postalAddresses.Append d d = new PostalAddress d.street = "Mi calle bonita" d.streetNumber = 8 d.streetFlat = 3 p.postalAddresses.Append d d = new PostalAddress d.street = "Princesa" d.streetNumber = 5 d.streetFlat = 5 p.postalAddresses.Append d For Each s As PostalAddress In p Listbox1.AddRow s.street + ", " + s.streetNumber.ToText + " Piso: " + s.streetFlat.ToText Next
Run the project, push the button and you will see how the
For 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 classic
For… Next loop, where we have to get the upper value (or limit) and use a variable as index to get every collection object we are interested in.
For more on this topic:
Javier Rodriguez has been the Xojo Spanish Evangelist since 2008, he’s also a Developer, Consultant and Trainer who has be using Xojo since 1998. He manages AprendeXojo.com and is the developer behind the GuancheMOS plug-in for Xojo Developers and the Snippery app, among others.