Operadores
## Objetivos de Aprendizaje
- Dominar operadores aritmeticos
- Comprender operadores de comparacion
- Trabajar con operadores logicos
- Usar operadores de rango
- Aprender operadores de asignacion
## Operadores Aritmeticos
### Matematica Basica
```swift
let a = 10
let b = 3
let suma = a + b // 13
let diferencia = a - b // 7
let producto = a * b // 30
let cociente = a / b // 3 (division entera)
let residuo = a % b // 1
```
### Division de Punto Flotante
```swift
let x: Double = 10.0
let y: Double = 3.0
let resultado = x / y // 3.333...
```
### Operadores Unarios
```swift
let negativo = -5
let positivo = +5 // Igual que 5
var contador = 0
contador += 1 // 1
contador -= 1 // 0
```
### Asignacion Compuesta
```swift
var puntuacion = 100
puntuacion += 10 // 110
puntuacion -= 20 // 90
puntuacion *= 2 // 180
puntuacion /= 3 // 60
puntuacion %= 5 // 0
```
## Operadores de Comparacion
### Igualdad
```swift
let igual = (10 == 10) // true
let diferente = (10 != 5) // true
```
### Relacionales
```swift
let menor = (3 < 5) // true
let mayor = (5 > 3) // true
let menorOIgual = (3 <= 3) // true
let mayorOIgual = (5 >= 5) // true
```
### Identidad
```swift
// === verifica si dos referencias apuntan a la misma instancia
class Perro {
var nombre: String
init(nombre: String) { self.nombre = nombre }
}
let perro1 = Perro(nombre: "Max")
let perro2 = perro1
let mismaInstancia = (perro1 === perro2) // true
let instanciaDiferente = (perro1 !== perro2) // false
```
## Operadores Logicos
### Y
```swift
let aprobo = true
let tieneCreditos = true
if aprobo && tieneCreditos {
print("Puede graduarse")
}
// Tabla de verdad:
// true && true = true
// true && false = false
// false && true = false
// false && false = false
```
### O
```swift
let esAdmin = false
let esModerador = true
if esAdmin || esModerador {
print("Tiene acceso")
}
// Tabla de verdad:
// true || true = true
// true || false = true
// false || true = true
// false || false = false
```
### NO
```swift
let estaDeshabilitado = false
if !estaDeshabilitado {
print("Esta habilitado")
}
// Tabla de verdad:
// !true = false
// !false = true
```
### Combinados
```swift
let edad = 25
let tieneLicencia = true
let tieneSeguro = true
if edad >= 18 && (tieneLicencia || tieneSeguro) {
print("Puede conducir")
}
```
## Operadores de Rango
### Rango Cerrado (...)
Incluye ambos extremos:
```swift
for indice in 1...5 {
print(indice) // 1, 2, 3, 4, 5
}
// Util para arreglos
let frutas = ["manzana", "banana", "cereza"]
for i in 0...2 {
print(frutas[i])
}
```
### Rango Semi-abierto (..<)
Excluye el ultimo extremo:
```swift
for indice in 0..<5 {
print(indice) // 0, 1, 2, 3, 4
}
// Comun con arreglos
for i in 0..= 90 ? "A" : puntuacion >= 80 ? "B" : puntuacion >= 70 ? "C" : "F"
```
## Operador de Fusión de Nil
Proporciona valor por defecto para opcionales:
```swift
let nombreOpcional: String? = nil
let nombreMostrar = nombreOpcional ?? "Anonimo"
// nombreMostrar = "Anonimo"
let nombreReal: String? = "Alicia"
let saludo = "Hola, \(nombreReal ?? "Invitado")"
// saludo = "Hola, Alicia"
```
## Operadores Bit a Bit
### NOT Bit a Bit
```swift
let bits: UInt8 = 0b10101010
let invertido = ~bits // 0b01010101
```
### AND Bit a Bit
```swift
let a: UInt8 = 0b1100
let b: UInt8 = 0b1010
let resultado = a & b // 0b1000
```
### OR Bit a Bit
```swift
let resultado = a | b // 0b1110
```
### XOR
```swift
let resultado = a ^ b // 0b0110
```
### Desplazamiento
```swift
let desplazado = a << 1 // 0b11000
let desplazadoDer = a >> 1 // 0b0110
```
## Precedencia de Operadores
### Niveles de Precedencia
| Nivel | Operadores |
|-------|-----------|
| Mas alto | Prefijo (a, b), Multiplicacion (*, /, %) |
| | Adicion (a, b), Desplazamiento (<<, >>) |
| | AND bit a bit (&) |
| | XOR bit a bit (^) |
| | OR bit a bit (`\|`) |
| | AND logico (&&) |
| | OR logico (`\|\|`) |
| Mas bajo | Ternario (a ? b : c), Asignacion (a = b) |
### Ejemplos
```swift
let resultado = 2 + 3 * 4 // 14, no 20
let resultado2 = (2 + 3) * 4 // 20
let x = true && false || true // true
```
## Operadores de Desbordamiento
### Comportamiento Predeterminado
```swift
let maxInt = Int.max
// maxInt + 1 // Bloqueo en tiempo de ejecucion!
```
### Uso de Operadores de Desbordamiento
```swift
let sumaDesbordamiento = maxInt &+ 1 // Envuelve alrededor
let productoDesbordamiento = 100 &* 100 // Envuelve en desbordamiento
```
### Comportamiento de Envolvimiento
## Operadores Personalizados
### Definir Operador
```swift
infix operator **
func **(base: Double, exponente: Double) -> Double {
return pow(base, exponente)
}
let resultado = 2 ** 3 // 8.0
```
### Precedencia y Asociatividad
```swift
infix operator **: MultiplicationPrecedence
precedencegroup MiPrecedencia {
higherThan: MultiplicationPrecedence
associativity: left
}
```
## Resumen
- Aritmeticos: `+`, `-`, `*`, `/`, `%`
- Comparacion: `==`, `!=`, `<`, `>`, `<=`, `>=`
- Logicos: `&&`, `||`, `!`
- Rango: `...` (cerrado), `..<` (semi-abierto)
- Ternario: `condicion ? verdadero : falso`
- Fusion de nil: `opcional ?? valorPorDefecto`
- Bit a bit: `&`, `|`, `^`, `~`, `<<`, `>>`
- Usar parentesis para claridad
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →