Continuando con la entrega anterior esta vez veremos los tipos de datos en Swift.
Principales tipos de datos:
- Int.
- Float.
- Double.
- String.
- Character.
- Bool.
Declarando variables y constantes. Podemos hacerlo de manera explícita o implícita.
// Variables var numEntero: Int = 33 var numReal = 23.6 var strNum = "56"; var strNumToInt = Int(strNum) var strCad: String = "ABC" var isFalse: Bool = 32 > 33 var isTrue = !isFalse // Constantes let MAX: Int = 200 let (x,y) = (2,4) let BANDERA: String = "EXIT" let monto = 234.00 let monto_total = monto / 10.0
Como se puede ver usamos ``var`` para declarar una variable mutable y ``let`` para constantes inmutables.
/* Declarar múltiples variables */ var a , b, c, d: Double a = 54.4 b = a - 21.5 c = b * 3.1 d = c + a
Incluso las variables pueden incluir caracteres Unicode:
let π = 3.14159 let 🐮 = "my cow"
¿Y qué con los arreglos? Podemos declararlos de dos formas:
let nombres: Array<String> = ["Maria", "Veronica", "Diana"] // O de esta otra forma let nombres: [String] = ["Maria", "Veronica", "Diana"]
Código completo:
variables.swift
func main() { print("\t [ Fundamentos en Swift ]") // Variables var numEntero: Int = 33 var numReal = 23.6 var strNum = "56"; var strNumToInt = Int(strNum) var strCad: String = "ABC" var isFalse: Bool = 32 > 33 var isTrue = !isFalse // Constantes let MAX: Int = 200 let (x,y) = (2,4) let BANDERA: String = "EXIT" let monto = 234.00 let monto_total = monto / 10.0 /* Declarar múltiples variables */ var a , b, c, d: Double a = 54.4 b = a - 21.5 c = b * 3.1 d = c + a let π = 3.14159 let 🐮 = "my cow" let nombres: Array<String> = ["Maria", "Veronica", "Diana"] // O de esta otra forma //let nombres: [String] = ["Maria", "Veronica", "Diana"] print("numEntero: ", numEntero) if isTrue{ print("strCad: ", strCad) print("strNumToInt: ", strNumToInt) print("numReal: ", numReal) print("strNum: ", strNum) isTrue = false } print("MAX: ",MAX) print("x: ",x) print("y: ",y) print("Bandera: ",BANDERA) print("Monto total: ", monto_total) print("a: ", a) print("b: ", b) print("c: ", c) print("d: ", d) print("PI: ",π) print("cow: ",🐮) print("nombre: ",nombres[1]) } main();
Ejecutamos:
$ swift variables.swift
Salida:
[ Fundamentos en Swift ] numEntero: 33 strCad: ABC strNumToInt: Optional(56) numReal: 23.6 strNum: 56 MAX: 200 x: 2 y: 4 Bandera: EXIT Monto total: 23.4 a: 54.4 b: 32.9 c: 101.99 d: 156.39 PI: 3.14159 cow: my cow nombre: Veronica
Continuaremos con esta serie en próximas entregas.
Enlaces:
https://alquimistadecodigo.blogspot.com/2025/10/swift-el-lenguaje-de-programacion-de.htmlhttps://www.hackingwithswift.com/read/es/0/3/tipos-de-datos

Comentarios
Publicar un comentario