22 Mar

Tuples and enums in Swift are cool ;)

In my last entry I did complain a little about some of Swift wonders I have recently discovered, so today I’m going to look at the bright side of Swift, just to keep the balance ;)

I’m going to focus on two data structures: tuples and enumerations. Again I look at the language from my c# point of view and I’ve noticed that it’s more fun to use these two in Swift than in .net :)

Tuples

Tuples group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.

A tuple is like an ordered list of items of any kind. I sometimes do use tuples when I’m not in a mood of creating yet another structure (== too lazy to do this). The most common scenario in my case is while dealing with Silverlight’s completed events for WCF service client calls. Sometimes there’s a need to pass an object while calling a service method and play around with the object later on, when the method completes (Silverlight is asynchronous). Sometimes the object consists of few values taken from application’s different properties rather than a single object. And this is a time when I wonder if it’s complicated enough to create a new structure or a tuple will do. Why? Because using a tuple in this case means that the code becomes hard to read. Let me show you an example:

void SomeMethod_Completed(object sender, CompletedEventArgs e)
{
    Tuple<Guid, string> userState = (Tuple<Guid, string>)e.UserState;
    var firstParam = userState.Item1;
    var secondParam = userState.Item2;
}

Can you tell from reading the above snippet what is a firstParam and what is a secondParam? What do they represent? Me neither. I have to go back to a place in code where the function is being called, what parameters are passed and what these two guys are really about. The thing I miss here is having a readable label, like: id or name. In Swift you can create a named tuple:

let person = (id: 1, name: "Jon Snow");
print(person.name);

and access tuple’s value by its label name. This is really convenient and helpful. You can make a tuple a return value of a function, no need to create some extra structures. You can do this of course also in c# but the result is, let’s say, less self explanatory ;)

Enumerations

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.
If you are familiar with C, you will know that C enumerations assign related names to a set of integer values. Enumerations in Swift are much more flexible, and do not have to provide a value for each case of the enumeration. If a value (known as a “raw” value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type.

This is true, I know enums as a set of labeled integer values. Let me show you what you can do with enumerations in Swift:

enum Mood
{
	case happy, sad, inLove;

	var emoji: String
	{
		switch self
		{
			case .happy:
			return ":)"

			case .sad:
			return ":("

			case .inLove:
			return "<3"
		}
	}

	func gonnaCry() -> Bool
	{
		return self == .sad;
	}
}

You  can extend enum definition with properties and functions. I added a property which returns proper emoji for a mood and a function checking if current enumeration value equals sad. This results in following output:

Pretty cool, huh? Wait, there’s more.

enum Barcode
{
	case upc(Int, Int, Int, Int)
	case qrCode(String)
}

var productBarcode = Barcode.upc(8, 85909, 51226, 3);
productBarcode = .qrCode("ABCDEFGHIJKLMNOP");

The example shows you can define an enum that is either a tuple of four integer numbers or a string value. One variable can be assigned either value. Pretty impressive ;)

All quotes come from The Swift Programming Language (Swift 3.0.1), iBooks.