Structures vs Classes

This is another entry in the VS series where i breakdown the differences between closely related coding topics.

Here, we’re going to dig into the differences and similarities between structures and classes.

First let define the what these structures are in the first place.

let start with a Classes. Classes should be very familiar to anyone who dealt with any OOP(Object Oriented Programming) language. Lets start with the text book definition of what a class is :

class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).[1][2] In many languages, the class name is used as the name for the class (the template itself), the name for the default constructor of the class (a subroutine that creates objects), and as the type of objects generated by instantiating the class; these distinct concepts are easily conflated.

Lets decode this definition into lamens terms later, for now just keep the word “template” in mind.

Next let’s take a look at what Structures aka Structs are.

structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.

Now let’s see how are these data structures look like in code.

We’ll take a look at a simple struct as well as a simple class.

struct Table {  var materialsMadeOf:[String]  var color: String  var numOfLegs: Int}
class Person {  var name: String  var age: Int  var gender: String  init(name:String, age:Int, gender:String) {    self.name = name    self.age = age    self.gender = gender   }}

Now at first glance these two structures look almost identical.Both have a name that starts with a capital letter, both have 3 properties, but for those of you with the eagle eye, you may have noticed the difference. You noticed the obvious difference of the struct and class keywords and you may have noticed the class has a little extra; it has this init thing in it. get it has init … in it haha. Those are just a few of the differences lets get into the others.

  1. Inheritance: Classes are are like rich people who benefit greatly from assets being passed down to them and add very little of their own (this is equivalent to overriding an existing method or property) but still saying they’re self made. this is classes in a nutshell. Let’s take a look at this in action.

class Person {  var name: String  var age: Int  var gender: String  init(name:String, age:Int, gender:String) {    self.name = name    self.age = age    self.gender = gender    }}class Athlete: Person {   enum Sport {    case basketball, football, soccer  }   var sportPlayed:Sport   var gamesWon: Int   init(sportPlayed: Sport, gamesWon: Int, name: String, age: Int,        gender: String) {   self.gamesWon = gamesWon   self.sportPlayed = sportPlayed   super.init(name: name, age: age, gender: gender)    }}let lebron = Athlete(sportPlayed: .basketball, gamesWon: 5, name: "Lebron James", age: 34, gender: "M")
  1. part of 1 — Initialization: one of the big differences between classes and structs is how we create instances of them. the eagle eyed readers noticed that the class structure had init.. in it and that the struct didn’t. this is because structs come with a member wise initializer which is swift’s way of saving you time from creating a method yourself that assigns values to the properties within your struct. Structs gives you this as a freebie! Classes do not have this and all will require a custom init method to set values to the properties within it.

class Person {  var name: String  var age: Int  var gender: String  init(name:String, age:Int, gender:String) {    self.name = name    self.age = age    self.gender = gender    }}let Batman = Person(name: "Bruce Wayne", age:33, gender: "Male")Batman.name // Bruce WayneBatman.age // 33Batman.gender // Male
  1. Copying: Another difference is how we go about copying structs vs classes. we’ll first need to understand that classes are a reference type and that structs are a value types. Now what does that mean. first let us take a look at this examples with classes.

class TV {  enum Size {  case small  case medium  case large}enum Brand {  case Sony  case Samsung  case LG  case Vizio}var brand:Brand?var size: Sizevar isHD: Boolinit(brand:Brand?, size:Size, isHD:Bool) {  self.brand = brand  self.size = size  self.isHD = isHD }}var vizio = TV(brand: nil, size: .medium, isHD: false)var randomBrand = viziorandomBrand.isHD = trueprint(randomBrand.isHD) // returns trueprint(vizio.isHD) // returns true as well

<iframe src=”https://giphy.com/embed/l36kU80xPf0ojG0Erg" width=”480" height=”268" frameBorder=”0" class=”giphy-embed” allowFullScreen></iframe><p><a href=”https://giphy.com/gifs/reaction-l36kU80xPf0ojG0Erg">via GIPHY</a></p>

As you can see both randomBrand and vizio are returning true even though we initially set the isHD property on vizio to false. This is because classes are reference types. which in this case means that both these instances are pointing to the same place in memory. essentially they are sharing the same instance of the class TV.

This isn't the case with structs as they are value types meaning that each time you copy a struct. A unique place in memory is allocated for it along with its values. as you can see below.

struct Animal {  let legs: Int  let hasFur: Bool  let type: String}let sparky = Animal(legs: 4, hasFur: true, type: "Dog")print(sparky)// prints Animal(legs: 4, hasFur: true, type: "Dog")

3. Deinitialization : classes can be deinitialized, and therefore a method can run whenever a class is taken out of memory. for example a deinit method can run when a class is removed from memory something a struct cannot do. Struct don’t have this functionality.

let us take a look at an example of deinitialization: In this example “bye, See you later” will print to the console.

class TV {   enum Size {     case small     case medium     case large   }   enum Brand {     case Sony     case Samsung     case LG     case Vizio   }   var brand:Brand?   var size: Size   var isHD: Bool   init(brand:Brand?, size:Size, isHD:Bool) {     self.brand = brand     self.size = size     self.isHD = isHD   }   deinit {     print("bye, see you later")  }}

In Summary:

Structs and Classes are very similar to each-other, but there are differences. The main differences being InheritanceInitializationDeinitialization and how they are copied.

More from Clyde Freeman

iOS Developer // Launch Academy Grad // Serial Manga doodle and self proclaimed super villain

Jan 20

Photo by Kelli McClintock on Unsplash

if let vs guard let

If your coding journey started anything like mine, you had no idea what if let or guard let was! After reading through resources and putting both into practice I still didn't really understand the difference. So, I’m here to make that more clear for the people who can relate.

First off, what is if let or guard let?

if let and guard let are simply Swift’s way of unwrapping (revealing the value of a variable or constant which can contain nil) optional values. …

Previous
Previous

Networking in Swift

Next
Next

if let vs guard let