Link or Swim

I learned today that you can’t make a linked list in Swift using value types. The reason why ties into the pointers issue I was recently discussing.

Here’s how a linked list struct might look in C:

struct LinkedList {
	struct LinkedList *next;
	int data;
};

And here’s how you would do it in Swift:

struct LinkedList {
	var next: LinkedList?
	var data: Int
}

The difference is, in C, you can have a reference to a struct without making a copy — without it being the thing itself. By adding an asterisk and making it a pointer.

In Swift, you can’t do that. So a reference to another struct might as well be that other struct, even if it isn’t always, under the hood.

If I try to compile that Swift, I get the error “value type ‘LinkedList’ cannot have a stored property that references itself”.

If I change the declaration from struct to class, then it compiles fine, because the property representing the “next” instance is now a reference to it.

I wasn’t expecting this issue to come up again so soon in my work.

%d bloggers like this: