Self-learning Swift (1): Struct vs Class

The main difference between struct and class in the type, both of them are used to create object in Swift. Struct is a value type, it will create a copy of the object and Class is a reference type, it will create a pointer to the object.

Class - reference type:

class Music {
    var genre: String
    var composer: String
    var year: Int

    init(genre: String, composer: String, year: Int) {
        self.genre = genre
        self.composer = composer
        self.year = year
    }
}

var myMusic = Music(genre: "Heavy Metal", composer: "X-Japan", year: 1986)
var remixedMusic = myMusic

remixedMusic.genre = "Pop"
print(myMusic.genre)
//output: Pop
//the change of remixedMusic affect myMusic

Struct - value type:

struct Music {
    var genre: String
    var composer: String
    var year: Int

    init(genre: String, composer: String, year: Int) {
        self.genre = genre
        self.composer = composer
        self.year = year
    }
}

var myMusic = Music(genre: "Heavy Metal", composer: "X-Japan", year: 1986)
var remixedMusic = myMusic

remixedMusic.genre = "Pop"
print(myMusic.genre)
//output: Heavy Metal 
//the change of remixedMusic didn't affect myMusic

Another difference between class and struct is the capability of use inheritance, just like other programming languages, I can create a sub-class for a class

Class - inheritance example:

class GoodMusic: Music{
    var rating: Int

    init(genre: String, composer: String, year: Int, rating: Int) {
        self.rating = rating
        super.init(genre: genre, composer: composer, year: year)
    }
}

//Real-life example:
class MyButton: UIButton{
//to customize my own button by inheritage SwiftUI's original button
}
ClassStruct
Reference TypeValue Type
Inheritance✅no-inheritance❌
Heavy, Slow❌Light, performance✅

To conclude:

Class:

  • When I need reference type

  • When I need inheritance

Struct:

  • When I need value type

  • When I need performance

  • Main used in creating SwiftUI