Pobresito de edgar jejeje…
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
Optional chaining is a technique that becomes a powerful ally, especially when we need to access, read or modify properties and methods in Swift, which can potentially be null. It is a process that simplifies the management of optional values, allowing to avoid forced errors and ensuring that the code is executed safely. This is particularly beneficial in avoiding the imprudent use of the forced unpack operator !
, which although fast, is risky if a non-null value is not guaranteed.
To illustrate how optional chaining works, let's consider the following example in Swift. Here, we create two classes: Person
and Residence
. The residence
property in Person
is optional, which means that a person might not have a residence defined at any given time.
class Person { var residence: Residence?}
class Residence { var numberOfRooms = 1 // Definition with a default number of rooms}
Suppose we have an instance of Person
, let's call it edgar
, which initially does not have a residence assigned to it:
var edgar = Person()
Trying to access the number of rooms directly could result in an error, since residence
is null. This is where the optional chaining comes into play:
{if let roomCount = edgar.residence?.numberOfRooms { print("Edgar's house has room(s).")} else { print("Edgar has no house.")}
This technique allows you to check if residence
has a value before attempting to access numberOfRooms
. If residence
is null, the code inside the else
block will be executed.
Optional chaining provides several advantages, which not only make the code safer, but also more elegant:
Yes, multiple optional values can be chained consecutively. This means that, instead of checking only one optional property, you could check successively properties that depend on each other.
Let's see an example of optional chaining in two levels:
class Address { var streetName: String?}
class Residence { var address: Address?}
var edgar = Person()edgar.residence = Residence()
if let streetName = edgar.residence?.address?.streetName { print("The address is \(streetName).")} else { print("Could not find the address.")} }
This approach simplifies the handling of property strings that can optionally be null, ensuring that the process is safe and clean.
Optional chaining should be considered in any case where handling potentially null values in complex data structures is necessary. This is particularly true in environments where optional properties may exist, such as data that depends on network functionality or databases with partial entries.
Using this technique not only enhances code robustness, but also promotes better programming practices in Swift. With the correct implementation of optional chaining, developers can transform potential weaknesses in their code into areas of safety and efficiency.
So, as you continue your programming journey, don't forget to consider optional chaining as a fundamental tool for managing null values safely and efficiently. Practice, curiosity and continuous learning are your best allies as a developer, so keep exploring!
Contributions 4
Questions 0
Pobresito de edgar jejeje…
Me alegra el hecho de que Edgar pudo comprarse su casa jajaja
Esta es una de las cosas mas interesantes del lenguage swift ya que con la Optional Chaining nos evitamos errores de nulos sobre todo el famoso “Pyramid of doom” muy comun en lenguajes como java.
Cada like es un cuarto más para Edgar!
Want to see more contributions, questions and answers from the community?