I can see that in some languages like swift there are both, however, I do not understand very well what the difference is.
I am learning the language and it is very important to learn everything you have.
I can see that in some languages like swift there are both, however, I do not understand very well what the difference is.
I am learning the language and it is very important to learn everything you have.
This is a question that can be answered with RTFM , but as a summary we can establish some differences:
class
are ReferenceType
, the struct
are ValueType
(more info here ) class
can be Extended, the struct
no. struct
are more commonly used to encapsulate data. struct
outside of its scope (passing it as a parameter, for example) makes a copy of the struct in the new scope, instead of pointing to the struct
already created. When to use a class and when to use a struct?
This question is very general, but we can say that, if you need your instance out of its original place, then you need a class
as a struct
It does not work for that.
Both the class and the structure can do:
The class can only do:
Here is an example with a class
. Notice how when the name is changed, the instance to which both variables refer is updated. Juan
is now Pedro
, in all parts that were once referred to Juan
.
class AlgunaClass {
var name: String
init(name: String) {
self.name = name
}
}
var aClass = AlgunaClass(name: "Juan")
var bClass = aClass // aClass y bClass //ahora hacen referencia a la misma instancia!
bClass.name = "Pedro"
println(aClass.name) // "Pedro"
println(bClass.name) // "Pedro"
And now with a struct
we see that the values are copied and each variable maintains its own set of values. When we set the name Pedro
, the structure Juan
in Struct
is not modified.
struct AlgunaStruct {
var name: String
init(name: String) {
self.name = name
}
}
var aStruct = AlgunaStruct(name: "Juan")
var bStruct = aStruct // ¡aStruct y bStruct son dos estructuras con el mismo valor!
bStruct.name = "Pedro"
println(aStruct.name) // "Juan"
println(bStruct.name) // "Pedro"
So, to represent a complex entity with a state, a class
is impressive. But for values that are simply a measure or bits of related data, struct
makes more sense so you can easily copy them and calculate with them or modify the values without fear of side effects.
SO Source: structure vs. class in swift language