Tuples vs Optionals – a Beginner’s approach

1. Introduction

Computer programming is about solving problems and getting things done the right way. However, as a beginner, you don’t care how you do it as long as you get it done. It works, so why bother tackling it in a completely different way after all?

The biggest challenge you face when discovering new programming paradigms is changing the way you think. This can be scary at first because you are used to doing things in a certain way and now you suddenly feel overwhelmed. It takes time and patience to get used to anything new but it’s worth doing it in the long run – being able to choose the right technique for a certain problem is a skill that any software developer should have in his toolbox.

2. The challenge

Your task for this tutorial is an easy one: remove a certain element from a given array. Before diving into coding, think how you would solve the problem and break it into steps. This is how I would do it:

  • create the array and populate it with default values;
  • create the number variable and assign its value;
  • loop through the array and do three things for each iteration:
    • extract the current item from the array;
    • test if it’s equal to the number and go to the next iteration if the test doesn’t succeed;
    • remove it from the array and exit the loop if the test succeeds;
  • print the array to the console;

That’s it for the algorithm – let’s move on to the implementation.

3. The optional implementation

Fire up Xcode and open a playground. Delete everything from it and add this line to kick things off:

var array = [1, 2, 3, 4, 5]

This line creates a variable array and assigns its default values – it’s variable because you are going to change its values soon.

Note: There are many different ways of creating arrays in Swift – this is the easiest approach of all because it uses type inference to determine the array’s type – Int in this case.

Now create the number variable and assign its value:

var number = 3

This line creates a variable and sets its value to one of the array’s elements. It’s variable because you are going to change its value soon.

Note: There are many different ways of creating variables in Swift – this is the easiest approach of all because it uses type inference to determine the variable’s type – Int in this case.

Note: Feel free to change the variable’s value to anything else and see what happens.

Now loop through the array with the for in control flow statement:

for _ in array {

}

Note: You use the underscore since you ignore the sequence’s values.

Note: You can read more about loops here.

There are two things you should do in the loop’s body. First compute the current index and unwrap it with the guard let statement:

guard let index = array.indexOf(number) else {
        
    continue
    
}

The array’s indexOf method returns the current index as an optional, so you have to use optional binding before doing anything else with it. If the index’s corresponding item isn’t the given number, the unwrapping process fails since the optional’s value is nil, so you go to the next iteration with the continue statement.

Note: You can read more about the guard statement here.

Next remove the element at the current index from the array and exit the loop with the break statement – no need to test the remaining values anymore:

array.removeAtIndex(index)
    
break

Note: You could also unwrap the index like this using the if let statement – the initial version takes the happy path approach:

if let index = array.indexOf(number) {
        
    array.removeAtIndex(index)
        
    break
        
 }

Finally, print the array to the console:

print(array, terminator: "")

Note: There are other ways to print to the console as well – this approach doesn’t print the newline “\n” character in the playground.

That’s it – let’s analyse the implementation.

4. The optional implementation analysed

The optional implementation focuses on the array’s indexes instead of values and requires optional binding – let’s take a different approach with tuples.

5. The tuple implementation

Add this line to the playground to get started:

number = 4

Here you set the number variable’s value to one of the array’s remaining items.

Next loop through the array:

for (index, value) in array.enumerate() {

}

The array’s enumerate method returns a tuple which contains the current index and value.

There are two things you should do inside the loop’s body. First test if the current value is equal to the number and advance to the next iteration if the test doesn’t succeed:

guard value == number else {
        
    continue
        
}

Now remove the value at the associated index and exit the loop:

array.removeAtIndex(index)
    
break

Note: You can also do it like this:

if value == number {
        
   array.removeAtIndex(index)
        
   break
 
}

Finally, print the array to the console:

print(array, terminator: "")

That’s it – let’s analyse the implementation.

6. The tuple implementation analysed

The tuple implementation focuses on the array’s values instead of indices and doesn’t require optional binding.

7. Tuples vs optionals comparison

Tuples advantages:

  • doesn’t require optional binding

Tuple disadvantages:

  • focuses on array values instead of indexes

Optional advantages:

  • focuses on array indices instead of values

Optional disadvantages:

  • requires optional binding

8. Conclusion

Both paradigms have their pros and cons – feel free to try them both and choose the one that suits you best. Happy coding! 🙂

Note: All the code in this tutorial was tested with a playground in Xcode 7.2 and Swift 2.1 (Download).

Note: This tutorial was inspired by a challenge from the excellent raywenderlich.com Swift Apprentice book.

Advertisements
Posted in Swift

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Enter your email address to receive notifications of new posts by email.

Simple Programmer
%d bloggers like this: