Tipos de datos rápidos (con ejemplos)

En este tutorial, aprenderá sobre los diferentes tipos de datos que admite el lenguaje de programación Swift y los usará al crear una variable o una constante.

Un tipo de datos es el tipo de datos (valor) que una variable o constante puede almacenar en él. Por ejemplo, en el artículo Variables y constantes de Swift, creó una variable y una constante para almacenar datos de cadena en la memoria.

Estos datos pueden ser un texto / cadena ("Hola") o un número (12.45) o solo bits (0 y 1). La definición del tipo de datos garantiza que solo se almacene el tipo de datos definido.

Veamos un escenario:

Suponga que quiere crear un juego. Dado que la mayoría de los juegos muestran la puntuación más alta y el nombre del jugador después de que se completa, debes almacenar estos dos datos para tu juego.

La puntuación más alta es un número (por ejemplo, 59) y el nombre del jugador una cadena (por ejemplo, Jack). Puede crear dos variables o constantes para almacenar los datos.

En Swift, esto se puede hacer declarando variables y el tipo de datos como:

 var highScore: Int = 59 var playerName: String = "Jack"

Aquí, declaramos la variable highScore de tipo Intque almacena el valor 59. Y, la variable playerName de tipo Stringque almacena el valor Jack.

Sin embargo, si haces algo como esto:

 var highScore: Int = "Jack"

Obtendrá un error de tiempo de compilación que indica que no se puede convertir el valor del tipo 'Cadena' al tipo especificado 'Int' .

Es porque declaró highScore para almacenar un valor entero pero colocó una cadena en él. Este error garantiza que highScore solo pueda almacenar un número y no el nombre del jugador.

Tamaño de un tipo de datos

Otra parte importante de un tipo de datos es su tamaño. Esto especifica el tamaño de los datos que se pueden almacenar en una variable o constante determinada.

El tamaño de un tipo se mide en términos de bits y puede almacenar valores de hasta 2 bits . Si no conoce Bit, considérelo un valor que sea 0 o 1.

Entonces, para un tamaño de tipo = 1 bit, solo puede almacenar hasta 2 1 = 2, dos valores: 0 o 1. Por lo tanto, un sistema de 1 bit para un programa de letras puede interpretar 0 como a / 0 y 1 como b / 1.0.

 0 -> a o 0 1 -> bo 1

Asimismo, un sistema de dos bits puede almacenar hasta 2 2 = 4 valores: (00,01,10,11) y cada combinación se puede representar como:

 00 -> a o 0 01 -> bo 1 11 -> c o 2 10 -> do 3

Para un sistema de bits, puede almacenar un máximo de 2 n valores en él.

Tipos de datos rápidos

Los tipos de datos más comunes que se utilizan en swift se enumeran a continuación:

Bool

  • La variable / constante declarada de tipo Bool puede almacenar solo dos valores trueo false.
  • Valor predeterminado : falso
  • Se utiliza con frecuencia cuando se trabaja con if-elsedeclaraciones. El artículo Swift if else lo cubre en detalle.

Ejemplo 1: tipo de datos booleanos

 let result:Bool = true print(result)

Cuando ejecute el programa, la salida será:

 cierto

Entero

  • La variable / constante declarada de tipo entero puede almacenar números enteros tanto positivos como negativos, incluido el cero sin componentes fraccionarios.
  • Valor predeterminado : 0
  • Tamaño : 32/64 bits depende del tipo de plataforma.
  • Rango : -2,147,483,648 a 2,147,483,647 (plataforma de 32 bits)
    -9223372036854775808 a 9223372036854775807 (plataforma de 64 bits
  • Hay muchas variantes de Entero type.eg UInt, Int8, Int16etc. El más común que se utiliza es de Int.
  • Si usted tiene un requisito para especificar el tamaño / tipo de número entero una variable / constante puede llevar a cabo, se puede almacenar más específicamente usando UInt, Int8, Int16etc., que vamos a explorar más adelante.

Ejemplo 2: tipo de datos entero

 var highScore:Int = 100 print(highScore) highScore = -100 print(highScore) 

Cuando ejecute el programa, la salida será:

 100 -100 

En el ejemplo anterior declaramos una variable highScore de tipo Int. Primero, le asignamos un valor de 100, por lo que print(highScore)genera 100 en la pantalla.

Más tarde, cambiamos el valor a -100 usando el operador de asignación como highScore = -100tal, print(highScore)genera -100 en la pantalla.

Exploremos algunas variantes de Inttipo en Swift.

Int8

  • Variante de tipo Integer que puede almacenar números pequeños tanto positivos como negativos.
  • Valor predeterminado : 0
  • Tamaño : 8 bit
  • Rango : -128 a 127

Un Int8número entero puede almacenar en total 2 8 = (256) valores en él. es decir, puede almacenar números del 0 al 255, ¿verdad?

Yes, you are correct. But since, Int8 includes both positive and negative numbers we can store numbers from -128 to 127 including 0 which totals to 256 values or numbers.

 var highScore:Int8 = -128//ok highScore = 127 //ok highScore = 128 // error here highScore = -129 //error here 

You can also find out the highest and lowest value a type can store using .min and .max built in Swift functions.

Example 3: Max and Min Int8 data type

 print(Int8.min) print(Int8.max) 

When you run the program, the output will be:

 -128 127

UInt

  • Variant of Integer type called UInt (Unsigned Integer) which can only store unsigned numbers (positive or zero).
  • Default Value: 0
  • Size: 32/64 bit depends on the platform type.
  • Range: 0 to 4294967295 (32 bit platform)
    0 to 18446744073709551615 (64 bit platform)

Example 4: UInt data type

 var highScore:UInt = 100 highScore = -100//compile time error when trying to 

The above code will give you a compile time error because a Unsigned Integer can only store either 0 or a positive value. Trying to store a negative value in an Unsigned Integer will give you an error.

Float

  • Variables or Constants declared of float type can store number with decimal or fraction points.
  • Default Value: 0.0
  • Size: 32 bit floating point number.
  • Range: 1.2*10-38 to 3.4 * 1038 (~6 digits)

Example 5: Float data type

 let highScore:Float = 100.232 print(highScore) 

When you run the program, the output will be:

 100.232

Double

  • Variables / Constants declared of Double type also stores number with decimal or fraction points as Float but larger decimal points than Float supports.
  • Default value : 0.0
  • Size: 64-bit floating point number. (Therefore, a variable of type Double can store number with decimal or fraction points larger than Float supports)
  • Range: 2.3*10-308 to 1.7*10308 (~15 digits)

Example 6: Double data type

 let highScore:Double = 100.232321212121 print(highScore) 

When you run the program, the output will be:

 100.232321212121

Character

  • Variables/Constants declared of Character type can store a single-character string literal.
  • You can include emoji or languages other than english as an character in Swift using escape sequence u(n) (unicode code point ,n is in hexadecimal).

Example 7: Character data type

 let playerName:Character = "J" let playerNameWithUnicode:Character = "u(134)" print(playerName) print(playerNameWithUnicode) 

When you run the program, the output will be:

 J Ĵ

String

  • Variables or Constants declared of String type can store collection of characters.
  • Default Value: "" (Empty String)
  • It is Value type. See Swift value and Reference Type .
  • You can use for-in loop to iterate over a string. See Swift for-in loop.
  • Swift also supports a few special escape sequences to use them in string. For example,
    • (null character),
    • \ (a plain backslash ),
    • (a tab character),
    • v (a vertical tab),
    • (carriage return),
    • " (double quote),
    • \' (single quote), and
    • u(n) (unicode code point ,n is in hexadecimal).

Example 8: String data type

 let playerName = "Jack" let playerNameWithQuotes = " "Jack "" let playerNameWithUnicode = "u(134)ack" print(playerName) print(playerNameWithQuotes) print(playerNameWithUnicode) 

When you run the program, the output will be:

 Jack "Jack" Ĵack 

See Swift characters and strings to learn more about characters and strings declaration, operations and examples.

In addition to this data types, there are also other advanced data types in Swift like tuple, optional, range, class, structure etc. which you will learn in later chapters.

Things to remember

1. Since Swift is a type inference language, variables or constants can automatically infer the type from the value stored. So, you can skip the type while creating variable or constant. However you may consider writing the type for readability purpose but it’s not recommended.

Example 9: Type inferred variable/constant

 let playerName = "Jack" print(playerName) 

Swift compiler can automatically infer the variable to be of String type because of its value.

2. Swift is a type safe language. If you define a variable to be of certain type you cannot change later it with another data type.

Ejemplo 10: Swift es un tipo de lenguaje seguro

 let playerName:String playerName = 55 //compile time error 

El código anterior creará un error porque ya especificamos que la variable playerName va a ser una String. Entonces no podemos almacenar un número entero en él.

Articulos interesantes...