1

The only thing I found is that a struct cannot inherit but a class does, and that a struct is passed by value while a class is passed by reference, but I couldn't understand what is that exactly. Can someone explain it please or give me an example?

Hamish
  • 78,605
  • 19
  • 187
  • 280

2 Answers2

9
class Car {
    var name: String

    init(name:String){
        self.name = name
    }
}

var carA = Car(name: "BMW")
var carB = carA
//now I will change carB
carB.name = "Nissan"
print(carA.name) //This will print Nissan


struct CarStruct {
    var name: String

    init(name: String){
        self.name = name
    }
}

var carC = CarStruct(name: "BMW")
var carD = carC
//now I will change carB
carD.name = "Nissan"
print(carC.name) //This will print BMW

As you can see both CarA and CarB are pointing to the same reference so if one changes the other change because the reference is changing, while in CarC and CarD which are structs they are copies of each other each with its value.

Artem Stepanenko
  • 3,423
  • 6
  • 29
  • 51
Jaafar Barek
  • 420
  • 3
  • 9
1

According to the very popular WWDC 2015 talk Protocol Oriented Programming in Swift video, Swift provides a number of features that make structs better than classes in many circumstances.

Structs are no more limited to just a set of fields holding some values.

Instead, Swift’s structs have quite the same capabilities as classes — except inheritance — but instead are value-types (so copied every time you pass them in another variable, much like Int for example) whereas classes are reference-types, passed by reference instead of being copied, like in Objective-C.