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?

1
  • Major: classes are reference type while Struct are value type Commented Apr 28, 2017 at 8:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments