what is the difference between a class and a structure

0

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.

    
asked by Kelly Hécate Villa 23.06.2018 в 05:30
source

2 answers

1

This is a question that can be answered with RTFM , but as a summary we can establish some differences:

  • The class are ReferenceType , the struct are ValueType (more info here )
  • The struct are stored in the stack, the classes in the Heap, so they are much faster.
  • The class can be Extended, the struct no.
  • struct are more commonly used to encapsulate data.
  • Using a 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.

    
answered by 23.06.2018 в 06:50
0

Both the class and the structure can do:

  • Define properties to store values
  • Define methods to provide functionality
  • Be extended
  • According to the protocols
  • Define intializers
  • Define subscripts to provide access to your variables

The class can only do:

  • Heritage
  • Type of foundry
  • Define dehumidifiers
  • Allow reference counting for multiple references.

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

    
answered by 23.06.2018 в 16:27