Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
14 Hrs
46 Min
40 Seg

Estructuras vs Clases

2/27
Resources
Transcript

What are structures and classes in object-oriented programming?

Object-oriented programming (OOP) is an essential pillar in the world of modern programming. This approach organizes software into units called "objects", which allow to store concrete data and behaviors. In this context, it is essential to understand the differences and similarities between two concepts: structures and classes. They are used to define and organize data and functionalities in programming, but they have particular characteristics that you must master.

What are the similarities between structures and classes?

Both structures and classes share several commonalities that you should keep in mind:

  • Property storage: Both allow you to define properties that can be constants or variables within their body.
  • Definition of methods: Methods are functions associated to the structure or class and are used to manipulate the data they contain.
  • Initializers (Constructors): They are used to create instances of structures or classes, defining their initial state.
  • Functionality extension: You can extend structures and classes with new functionalities, allowing their adaptation to future needs.
  • Protocol conformance: Both can adhere to protocols, allowing you to implement functionality not found in the original structure or class.

How do frameworks differ from classes?

Although they share many similarities, structures and classes also have critical differences:

  • Inheritance: only classes can inherit from other classes, offering the ability to extend or specialize their functionality.
  • Casting: Classes allow reinterpreting values from one type to another, which is key to flexibility in programming.
  • Deinitializers: In classes, these functions are useful to free memory when an instance is no longer used, unlike structures that do not have this feature.
  • Reference Counting: It is a mechanism implemented in classes to track how many references exist to an object at runtime, crucial for memory management.

How are structures and classes created and used in Swift?

The syntax for defining a struct or class is quite similar in Swift. Here's how it's done:

Defining a struct

struct Resolution { var width: Int = 0 var height: Int = 0}

Definition of a class

class ModoVideo { var resolution = Resolution() var interlaced = false var frameRate = 0.0 var name: String? = nil}

The syntax is clear and defines structures as 'struct' and classes as 'class'. The choice between using a structure or a class will depend on the specific needs of your project.

Practical example: manipulating structures and classes

Suppose we create instances of these definitions. When we work with a structure, it behaves like a value type:

let resolutionSon = Resolution().

Modifying its properties is not possible if we instantiate it with let, since it turns it into an immutable constant. This is to ensure that the structure retains its values once assigned.

On the other hand, when using a class, even if it is declared with let, its internal properties can modify its value:

let modoVideoSon mode = ModoVideo()modoVideoSon.frameRate = 30.0 // Modifiable.

In this scenario, modoVideoSon can change its frameRate because a class is a reference type. This means that it works over a fixed space in memory that allows it to update the state of the instance.

Understanding these differences and similarities offers a significant advantage when designing more efficient and organized systems. We encourage you to continue exploring and practicing to master the fascinating world of object-oriented programming.

Contributions 11

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Ambas permiten almacenar datos y definir m茅todos, inicializadores (constructores) y pueden ser extendidas.

Clases:

  • Herencia
  • Casting
  • Desinicializador para liberar memoria
  • Reference counting: sistema que permite localizar cu谩ntos fragmentos de c贸digo est谩n usando una determinada variable, esta implementado para referenciar mas de una referencia por clase en tiempo de ejecuci贸n.

Sintaxis de una Estructura y una Clase


struct SomeStruct {
    // La definici贸n de la estructura
}

class SomeClass {
    // La definici贸n de la clase
}

Ejemplos


struct Resolution {
    var width = 0
    var height = 0
}

class VideoMode {
    var resolution = Resolution()
    var interlace = false
    var frameRate = 0.0
    var name: String?
}

let someResolution = Resolution()
let someVideoMode = VideoMode()

print(someResolution.width)
someVideoMode.resolution.width = 1280
print(someVideoMode.resolution.width)

//someResolution.width = 1280	// esto no se puede hacer porque fue declarada como constante.

someVideoMode.frameRate = 30.0
print(someVideoMode.frameRate)

Una estructura, una vez creada, ocupa un espacio de memoria y al declararla como constante, tiene que permanecer inmutable. Es por eso que esto no se puede realizar:

someResolution.width = 1280

En el caso de un objeto de una clase, lo que tengo no es el propio objeto sino la zona de la memoria que ocupa. Las variables que tenga en su interior, las computed properties o las stored properties, podr谩n ir cambiando si se han declarado como variables (var dentro de la clase.

mis apuntentes !!! y dure como una hora viendo esta clase para poder entender馃槄

Las estructuras y clases de Swift tienen muchas cosas en com煤n. Ambos pueden:

  • Definir propiedades para almacenar valores

  • Definir m茅todos para proporcionar funcionalidad.

  • Definir sub铆ndices para proporcionar acceso a sus valores utilizando la sintaxis de sub铆ndices

  • Definir inicializadores para configurar su estado inicial

  • Extenderse para expandir su funcionalidad m谩s all谩 de una implementaci贸n predeterminada

  • Cumplir con los protocolos para proporcionar una funcionalidad est谩ndar de cierto tipo

Las clases tienen capacidades adicionales que las estructuras no tienen:

  • La herencia permite que una clase herede las caracter铆sticas de otra.

  • La conversi贸n de tipos le permite verificar e interpretar el tipo de una instancia de clase en tiempo de ejecuci贸n.

  • Los desinicializadores permiten que una instancia de una clase libere cualquier recurso que haya asignado.

  • El recuento de referencias permite m谩s de una referencia a una instancia de clase.

Me gusta mucho el resumen de CS193p - Developing Apps for iOS. Es mas un resumen para tener claros los puntos que se explican con c贸digo. Lo escrib铆 como TRIP2FUM para recordarlo
Type: Value vs Reference
Reference: Copy vs ARC
Inheritance: No vs Single
Passed: Copied vs pointers
Paradigm: FP vs OOP
Free Init: all vars vs no vars
Mutability: explicitly vs Always
Usage: go to (code) vs MVVM ViewModel and UIKit

Para el que viene de otros lenguajes mobile como kotlin, las struct son las primas de las Data class de Kotlin.

Por fin llegue a este punto! Como va la comunidad de Swift en Platzi??

Me gusta mucho como explica estas cosas complejas, Profe :3

struct Resolution {
    var width = 0
    var height = 0
}
class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}
segun he entendido: debo utilizar una **estructura(struct)** cuando se quiera trabajar con datos que se copian y no necesitan herencia, mientras que una **clase(class)** cuando necesite compartir la misma instancia de un objeto o aprovechar la herencia y otros comportamientos propios de las clases

es como en typescript, para definiciones mas peque帽as usamos el type y para mas complejas o extensas simplemente creamos las clases

pero si declaramos la estructura como variable 驴se podr铆a modificar? 驴o una estructura es inmutable?