June 10, 2014

Swift Classes, Structs, Enums, and Tuples compared

Posted in Uncategorized tagged , , , , , , at 10:25 pm by tetontech

In Apple’s Swift book there is a chapter on Classes and Structs. The first major section of that chapter describes how Classes and Structs are the same and how they differ. There were a few things that they left out of the list. They also didn’t compare them to Enums and Tuples.

In this posting I’m going to display a table that compares all four types, but leaves out what Apple already has in their book. Including that information would clutter what I’m trying to get across. Please go look there to see more similarities and differences.

 

Classes

Structs

Enums

Tuples

size

includes sizeof elements includes sizeof elements

passing

by reference by value no passing by value

methods

can have can have can contain functions and closures

contained values

as properties as properties as constants as elements

calculated properties

supported supported no no

 

The size row is the result of observing the results of calling the C sizeof() function on classes structs and enums. Tuples can’t be passed to sizeof() so that result is deduced.

Enumerations are not passed. All the other types are passed by value or reference as shown in the table. The only variance from this rule is Arrays. As said in the book, they are passed by reference until, not unless, a modification to the Array is made that changes its length. Then a copy is made and you are dealing with a copy.

The methods  row has a blank in the Enum column. Enums can’t have methods but they can contained pre-built switches that can be accessed (See Apple’s Swift book for details).

Calculated properties are somewhat like methods that are accessed by a property name. There is no data storage, only a return from a method call.

There are more of these, such as subscript support, that I’ll be adding to this table as I explore further.

Advertisements

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

%d bloggers like this: