Tipi di dati Swift (con esempi)

In questo tutorial imparerai a conoscere i diversi tipi di dati supportati dal linguaggio di programmazione Swift e li utilizzerai durante la creazione di una variabile o di una costante.

Un tipo di dati è il tipo di dati (valore) che una variabile o una costante può memorizzare al suo interno. Ad esempio, nell'articolo Swift Variables and Constants, hai creato una variabile e una costante per memorizzare i dati della stringa nella memoria.

Questi dati possono essere un testo / stringa ("Hello") o un numero (12,45) o solo bit (0 e 1). La definizione del tipo di dati garantisce che venga archiviato solo il tipo di dati definito.

Diamo un'occhiata a uno scenario:

Supponi di voler creare un gioco. Poiché la maggior parte dei giochi mostra il punteggio più alto e il nome del giocatore al termine del gioco, è necessario memorizzare questi due dati per il gioco.

Il punteggio più alto è un numero (ad esempio 59) e il nome del giocatore una stringa (ad esempio Jack). È possibile creare due variabili o costanti per memorizzare i dati.

In Swift, questo può essere fatto dichiarando le variabili e il tipo di dati come:

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

Qui, abbiamo dichiarato una variabile highScore di tipo Intche memorizza il valore 59. E, playerName variabile di tipo Stringche memorizza il valore Jack.

Tuttavia, se fai qualcosa del genere:

 var highScore: Int = "Jack"

Si riceverà un errore in fase di compilazione che indica che non è possibile convertire il valore di tipo "String" nel tipo specificato "Int" .

È perché hai dichiarato highScore per memorizzare il valore intero ma hai inserito una stringa. Questo errore garantisce che HighScore possa memorizzare solo un numero e non il nome del giocatore.

Dimensioni di un tipo di dati

Un'altra parte importante di un tipo di dati è la sua dimensione. Specifica la dimensione dei dati che possono essere memorizzati in una determinata variabile o costante.

La dimensione di un tipo viene misurata in termini di bit e può memorizzare valori fino a 2 bit . Se non conosci Bit, pensalo come un valore che è 0 o 1.

Quindi, per una dimensione del tipo = 1 bit, può solo memorizzare fino a 2 1 = 2, due valori: 0 o 1. Quindi un sistema a 1 bit per un programma di lettere può interpretare 0 come a / 0 e 1 come b / 1.0.

 0 -> a o 0 1 -> bo 1

Allo stesso modo, un sistema a due bit può memorizzare fino a 2 2 = 4 valori: (00,01,10,11) e ogni combinazione può essere rappresentata come:

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

Per un sistema di bit, può memorizzare un massimo di 2 n valori in esso.

Tipi di dati rapidi

I tipi di dati più comuni utilizzati in swift sono elencati di seguito:

Bool

  • La variabile / costante dichiarata di tipo Bool può memorizzare solo due valori trueo false.
  • Valore predefinito : false
  • Viene spesso utilizzato quando si lavora con if-elsestatement. L'articolo Swift se altro lo copre in dettaglio.

Esempio 1: tipo di dati booleano

 let result:Bool = true print(result)

Quando esegui il programma, l'output sarà:

 vero

Numero intero

  • La variabile / costante dichiarata di tipo intero può memorizzare numeri interi sia positivi che negativi incluso lo zero senza componenti frazionarie.
  • Valore predefinito : 0
  • Dimensione : 32/64 bit dipende dal tipo di piattaforma.
  • Intervallo : da -2.147.483.648 a 2.147.483.647 (piattaforma a 32 bit) da
    -9223372036854775808 a 9223372036854775807 (piattaforma a 64 bit
  • Ci sono molte varianti di Integer type.eg UInt, Int8, Int16ecc Il più quello comune utilizzato è di Int.
  • Se si dispone di un requisito per specificare la dimensione / tipo di integer una variabile / costante può contenere, è possibile memorizzare più specificamente utilizzando UInt, Int8, Int16ecc, che ci accingiamo ad esplorare sotto.

Esempio 2: tipo di dati intero

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

Quando esegui il programma, l'output sarà:

 100-100 

Nell'esempio sopra abbiamo dichiarato una variabile highScore di tipo Int. Innanzitutto, gli abbiamo assegnato un valore di 100 in modo da visualizzare print(highScore)100 sullo schermo.

Successivamente, abbiamo modificato il valore in -100 utilizzando l'operatore di assegnazione in questo highScore = -100modo, print(highScore)restituisce -100 nella schermata.

Esploriamo alcune varianti di Inttipo in Swift.

Int8

  • Variante di tipo Integer che può memorizzare numeri piccoli sia positivi che negativi.
  • Valore predefinito : 0
  • Dimensioni : 8 bit
  • Intervallo : da -128 a 127

Un Int8numero intero può memorizzare complessivamente 2 8 = (256) valori in esso. cioè può memorizzare numeri da 0 a 255 giusto?

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.

Esempio 10: Swift è un linguaggio indipendente dai tipi

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

Il codice sopra creerà un errore perché abbiamo già specificato che la variabile playerName sarà una stringa. Quindi non possiamo memorizzare un numero intero in esso.

Articoli interessanti...