You don't have access to this class

Keep learning! Join and start boosting your career

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

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
3 Hrs
14 Min
11 Seg

Condicionales

4/25
Resources

What are conditionals in programming?

Conditionals are one of the fundamental pillars of programming. They allow our code to execute certain actions depending on whether or not a condition we define is met. Imagine that you want to display a message to the user depending on whether a student passed an exam based on his or her grade. If the grade is greater than or equal to a certain number, we display a pass message; otherwise, we display a fail message.

How is a conditional structured in Swift?

In Swift, the basic structure of a conditional begins with the word if, followed by the condition to be evaluated in parentheses. If the condition is met, the block of code between braces will be executed. If the condition is not met and we want to execute another block of code, we use the word else.

let note = 3 if note > 3 { print("It is greater than three") } else { print("It is not greater than three") }

How are mathematical operators used in conditionals?

Mathematical operators are essential for making comparisons within conditionals. Some examples are:

  • > Greater than
  • >= Greater than or equal to
  • < Less than
  • <= Less than or equal to
  • == Equal to
  • != Different from

These operators allow us to evaluate complex conditions and determine which set of instructions to execute.

if note &amp;gt;= 3 { print("Is greater than or equal to three") } else { print("Is not greater than or equal to three") }

How to evaluate multiple conditions?

Sometimes, we need to evaluate more than one condition to decide what actions to take. In these cases, it is common to use else if to include additional conditions.

let exempted = true if exempted || grade &amp;gt;= 3 { print("Congratulations, you passed the exam") } else { print("Sorry, see you next semester") } }

How to create complex conditionals?

For conditionals that require evaluating within certain ranges or several conditions at once, we can use grouping and logical operators.

let presento = true if presento &amp;amp;&amp;amp; (exempted || grade &amp;gt;= 3) { print("Congratulations, you passed the exam") } else { print("Sorry, you didn't pass") } }

Implementing complex conditionals

We can construct complex conditionals one after another to, for example, determine the quality of a grade.

let gradeTwo = 4 if gradeTwo &amp;gt;= 0 &amp;amp;&amp;amp; gradeTwo &amp;lt; 2 { print("You did very poorly on the exam.") } else if noteTwo &amp;gt;= 2 &amp;amp;&amp;amp;&amp;amp; noteTwo &amp;lt; 3 { print("Sorry, that was close") } else if noteTwo &amp;gt;= 3 &amp;amp;&amp;amp; noteTwo &amp;lt; 4 { print("You passed, but you can do better") } else if noteTwo &amp;gt;= 4 &amp;amp;&amp;amp; noteTwo &amp;lt;= 5 { print("Congratulations, you did very well") } else { print("System error") }

Test your knowledge by evaluating the equivalence of two strings in Swift. How would you handle sentence comparison? Share your ideas and experiences in the comments.

Contributions 10

Questions 0

Sort by:

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

![](https://static.platzi.com/media/user_upload/Captura%20de%20pantalla%202024-11-27%20a%20la%28s%29%206.41.33p.m.-ade5f819-d164-497c-926c-f63d3780fdf8.jpg) ```js Lo hice asi y en la consola funciona, nose si es la forma correcta, pero da con el resultado ```
**let** phrase: String = "Hello, World!" **let** phrase2: String = "Hello, World!" **var** isEqual: Bool = phrase.elementsEqual(phrase2) **if** (isEqual) { print("Equal") } **else** { print("Not Equal") }
No soy mucho de participar pero les dejo mi guia ```txt // Ejemplo 1: Uso b谩sico de if, else if y else let temperatura = 25 if temperatura > 30 { print("Hace mucho calor. Usa ropa ligera.") } else if temperatura >= 20 && temperatura <= 30 { print("El clima es agradable.") } else { print("Hace fr铆o. Usa un abrigo.") } // Ejemplo 2: Uso de operadores l贸gicos || (o) y && (y) let esFinDeSemana = true let tengoDinero = false if esFinDeSemana && tengoDinero { print("隆Vamos al cine!") } else if esFinDeSemana || tengoDinero { print("Podemos hacer algo en casa.") } else { print("Toca trabajar o ahorrar dinero.") } // Ejemplo 3: Comparaci贸n de n煤meros con operadores relacionales let edad = 18 if edad >= 18 { print("Eres mayor de edad.") } else { print("Eres menor de edad.") } // Ejemplo 4: Uso del operador ternario ? : let esMayor = edad >= 18 ? "S铆, puedes votar." : "No, a煤n no puedes votar." print(esMayor) // Ejemplo 5: Evaluando m煤ltiples condiciones con && y || let esEstudiante = true let tieneDescuento = false if esEstudiante && tieneDescuento { print("Tienes un descuento especial.") } else if esEstudiante || tieneDescuento { print("Podr铆as obtener un descuento.") } else { print("No tienes descuentos disponibles.") } // Ejemplo 6: Validaci贸n de cadenas de texto let usuario = "Admin" if usuario == "Admin" { print("Acceso concedido.") } else { print("Acceso denegado.") } // Ejemplo 7: Comparaci贸n de n煤meros negativos y positivos let numero = -5 if numero > 0 { print("El n煤mero es positivo.") } else if numero < 0 { print("El n煤mero es negativo.") } else { print("El n煤mero es cero.") } // Ejemplo 8: Comparaci贸n y manipulaci贸n de cadenas de texto let palabra1 = "Swift" let palabra2 = "swift" // Comparaci贸n sensible a may煤sculas y min煤sculas if palabra1 == palabra2 { print("Las palabras son iguales.") } else { print("Las palabras son diferentes.") } // Comparaci贸n ignorando may煤sculas y min煤sculas if palabra1.lowercased() == palabra2.lowercased() { print("Las palabras son iguales ignorando may煤sculas.") } // Uso del operador ternario con strings let mensaje = palabra1.count > 5 ? "Palabra larga" : "Palabra corta" print(mensaje) // Verificar si una cadena contiene otra let frase = "Bienvenido a Swift!" if frase.contains("Swift") { print("La frase menciona Swift.") } else { print("Swift no se menciona en la frase.") } ```
``` **let** sentenceOne = "Hey!馃檲" **let** sentenceTwo = "Hey!馃檲" **if** (sentenceOne.elementsEqual(sentenceTwo)) { print("The two sentences are equal!") } **else** { print("The two sentences are not equal!") } ```
**let** sentenceOne = "Hey!馃檲" **let** sentenceTwo = "Hey!馃檲" **if** (sentenceOne.elementsEqual(sentenceTwo)) { print("The two sentences are equal!") } **else** { print("The two sentences are not equal!") }
```js let nota = 10 if (nota >= 9) { print("La nota es mayor o igual a 9") }else { print( "no es mayor o igual a 9") } let eximido = false if(eximido || nota >= 8){ print("Pasaste el examen siendo eximido") } else { print("No pasaste el examen") } let assistance = true if(assistance && (eximido || nota >= 8)){ print("Y te presentaste al examen") }else { print("No te presentaste al examen") } let nota2 = 5 if(nota2 >= 0 && nota2 < 3){ print("Reprobaste, y muy mal") }else if (nota2 >= 3 && nota2 <= 5){ print("Casi lo logras") }else if (nota2 > 5 && nota2 <= 9){ print("Pasaste a justa medida") }else if (nota2 == 10){ print ("puntaje perfecto") }else { print("Hay un error en el sistema") } ```
```js var nota = 3 let eximido = false let siPresento = true if(nota == 3 && siPresento){ print("pasaste, pero pasaste raspando") } else if(nota > 3 || eximido && siPresento){ print("felicidades, pasaste") }else{ print("nos vemos de nuevo el proximo semestre") } ```
**var** nota = 3 **if**(nota == 3){ print("pasaste, pero pasaste raspando") } **else** **if**(nota > 3){ print("felicidades, pasaste") }**else**{ print("nos vemos de nuevo el proximo semestre") }
Bien, el caso es que puede hacerse con operadores ternarios y usando las diferentes funciones del tipo String: ```js constante.elementsEqual(constante2) ? print("\(constante) es igual a \(constante2)") : constante.lowercased().elementsEqual(constante2) ? print("\(constante.lowercased()) es igual a \(constante2)") : constante.lowercased().elementsEqual(constante2.lowercased()) ? print("\(constante.lowercased()) es igual a \(constante2.lowercased())") : print("\(constante) es diferente a \(constante2)") ```constante.elementsEqual(constante2) ? print("\\(constante) es igual a \\(constante2)") : constante.lowercased().elementsEqual(constante2) ? print("\\(constante.lowercased()) es igual a \\(constante2)") : constante.lowercased().elementsEqual(constante2.lowercased()) ? print("\\(constante.lowercased()) es igual a \\(constante2.lowercased())") : print("\\(constante) es diferente a \\(constante2)")
```js // Evaluar si una frase es igual a otra let frase1 = "Hola" let frase2 = "Hola1" if (frase1 == frase2){ print("Las frases son iguales") } else { print("Las frases no son iguales") } ```