lol, este ejemplo est谩 en la documentaci贸n de apple
Estructuras y Clases
Qu茅 aprender谩s sobre la programaci贸n orientada a objetos en Swift
Estructuras vs Clases
Estructuras: datos copiados por valor
Clases: datos referenciados
Tipos de Propiedades
Stored Properties
Lazy Stored Properties
Computed Properties
Computed Properties de s贸lo lectura
Property Observers
Type Properties
M茅todos, sub铆ndices y herencia
M茅todos de instancia
Mutating Methods
M茅todos de clase
Sub铆ndices
Matrices usando sub铆ndices
Herencia
Sobreescritura de variables y m茅todos
Inicializadores o constructores
Inicializadores
Nombres, etiquetas y optionals
Inicializadores en subclases
Failable Initializer
Destrucci贸n de objetos con deinit
Encadenamiento opcional
Optional Chaining
Clases ejemplo para Optional Chaining
Ejemplo pr谩ctico con Optional Chaining
Optional Chaining m煤ltiple
Conclusi贸n
Cierre del curso
You don't have access to this class
Keep learning! Join and start boosting your career
Destructors are a fundamental part of the object-oriented programming world. These special methods are automatically called when an object ceases to exist or is no longer needed, allowing us to perform cleanup tasks, such as freeing resources that are no longer needed. In the context of games, a concrete example is a player's inventory. If a player dies and his inventory is not destroyed, this can lead to resources being taken up even without need. Therefore, it is vital to know how to implement destroyers to handle these situations efficiently.
In Swift, we can define a destructor using the deinit
method. This method is called automatically when an object is about to be deleted. Below is an example implementation of a Player
class within a video game, where the coins held by the player should automatically return to the bank when it is destroyed.
class Bank { static var coinsInBank = 2000
static func distribute(coins: Int) -> Int { let numberOfCoinsToVend = min(coins, coinsInBank) coinsInBank -= numberOfCoinsToVend return numberOfCoinsToVend }
static func receive(coins: Int) { coinsInBank += coins }}
class Player { var coinsInPurse: Int
init(coins: Int) { coinsInPurse = Bank.distribute(coins: coins) }
deinit { Bank.receive(coins: coinsInPurse) }
func win(coins: Int) { coinsInPurse += Bank.distribute(coins: coins) }} }
Let's imagine that we create a player that starts with a certain amount of coins and accumulates more as he advances in the game. If the player is destroyed, we want to make sure that the coins are returned to the bank.
var player: Player? = Player(coins: 100)print(Bank.coinsInBank) // 1900 (2000 - 100)
player?.win(coins: 2000)print(Bank.coinsInBank) // 0, since all possible coins were distributed
player = nil // Player is destroyedprint(Bank.coinsInBank) // 2000, coins returned to the bank.
This example perfectly illustrates how destructors can facilitate automatic resource management within our applications, ensuring that any resource used is subsequently released when it is no longer needed.
Proper implementation and understanding of destructors is an essential skill for developers. By learning how to properly release resources, you not only optimize your applications, but also avoid potential bugs that may arise over time, fostering more efficient and effective software development.
Contributions 3
Questions 0
lol, este ejemplo est谩 en la documentaci贸n de apple
Lo hacemos como player opcional tambi茅n para poder destruirlo, si lo hiciera como let o como player requerido, sin el interrogante, nunca podr铆a destruirlo.
El desInicializador parece tener una funcionalidad a la que se encuentra en SQL en el borrado en cascada.
Want to see more contributions, questions and answers from the community?