Typy dat Swift (s příklady)

V tomto kurzu se dozvíte o různých datových typech, které programovací jazyk Swift podporuje, a použijte jej při vytváření proměnné nebo konstanty.

Datový typ je typ dat (hodnota), do kterého může proměnná nebo konstanta uložit. Například v článku Swift Variables and Constants jste vytvořili proměnnou a konstantu pro uložení dat řetězce do paměti.

Tato data mohou být text / řetězec („Hello“) nebo číslo (12,45) nebo jen bity (0 a 1). Definování datového typu zajistí, že se uloží pouze definovaný typ dat.

Podívejme se na scénář:

Předpokládejme, že chcete vytvořit hru. Jelikož většina her zobrazuje vysoké skóre a jméno hráče po dokončení hry, musíte si tyto dvě údaje pro svou hru uložit.

Nejvyšším skóre je číslo (např. 59) a jméno hráče řetězec (např. Jack). Pro uložení dat můžete vytvořit dvě proměnné nebo konstanty.

V Swiftu to lze provést deklarováním proměnných a datového typu jako:

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

Zde jsme deklarovali proměnnou typu highScore typu, Intkterá uchovává hodnotu 59. A proměnnou playerName typu, Stringkterá uchovává hodnotu Jack.

Pokud však něco takového uděláte:

 var highScore: Int = "Jack"

Získáte chybu kompilace s uvedením, že nelze převést hodnotu typu „String“ na zadaný typ „Int“ .

Je to proto, že jste deklarovali highScore k uložení celočíselné hodnoty, ale umístili jste do ní řetězec. Tato chyba zajišťuje, že highScore může ukládat pouze číslo a ne jméno hráče.

Velikost datového typu

Další důležitou součástí datového typu je jeho velikost. Určuje velikost dat, která lze uložit do dané proměnné nebo konstanty.

A Type je velikost se měří v podmínkách kousku a mohou ukládat hodnoty aľ 2 bity . Pokud nevíte o Bitu, uvažujte o něm jako o hodnotě 0 nebo 1.

Takže, pro typ size = 1 bit, je možné uložit pouze aľ, 2 1 = 2, dvě hodnoty: 0 nebo 1. takže 1 bit systém pro písmeno programu lze interpretovat jako 0/0 a 1 jako b / 1.0.

 0 -> a nebo 0 1 -> b nebo 1

Podobně může dvoubitový systém ukládat až 2 2 = 4 hodnoty: (00,01,10,11) a každou kombinaci lze reprezentovat jako:

 00 -> a nebo 0 01 -> b nebo 1 11 -> c nebo 2 10 -> d nebo 3

U bitového systému do něj může uložit maximálně 2 n hodnot.

Typy dat Swift

Níže jsou uvedeny nejběžnější datové typy používané ve swift:

Boole

  • Proměnná / konstanta deklarovaná typu Bool může uložit pouze dvě hodnoty buď truenebo false.
  • Výchozí hodnota : false
  • Často se používá při práci s if-elsepříkazem. Swift if else article covers in detail about it.

Příklad 1: Booleovský datový typ

 let result:Bool = true print(result)

Když spustíte program, výstup bude:

 skutečný

Celé číslo

  • Proměnná / konstanta deklarovaná celočíselným typem může ukládat celá čísla kladná i záporná včetně nuly bez zlomkových složek.
  • Výchozí hodnota : 0
  • Velikost : 32/64 bitů závisí na typu platformy.
  • Rozsah : -2 147 483 648 až 2 147 483 647 (32bitová platforma)
    -9223372036854775808 až 9223372036854775807 (64bitová platforma)
  • Existuje mnoho variant Integer type.eg UInt, Int8, Int16atd. Nejběžnější použití je Int.
  • Máte-li požadavek určit velikost / typ integer proměnná / konstanta může držet, můžete ukládat to konkrétně použití UInt, Int8, Int16atd., Které budeme zkoumat dále.

Příklad 2: Celočíselný datový typ

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

Když spustíte program, výstup bude:

 100-100 

Ve výše uvedeném příkladu jsme deklarovali proměnnou highScore typu Int. Nejprve jsme jej přiřadili s hodnotou 100, takže print(highScore)výstupy 100 na obrazovce.

Později jsme změnili hodnotu na -100 pomocí operátoru přiřazení, highScore = -100takže print(highScore)na obrazovce bude výstup -100.

Prozkoumejme některé varianty Inttypu v Swiftu.

Int8

  • Varianta typu Integer, která může ukládat kladná i záporná malá čísla.
  • Výchozí hodnota : 0
  • Velikost : 8 bitů
  • Rozsah : -128 až 127

Int8Celé číslo lze uložit celkem 2 8 = (256) hodnoty v něm. tj. může ukládat čísla od 0 do 255, že?

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.

Příklad 10: Swift je typově bezpečný jazyk

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

Výše uvedený kód vytvoří chybu, protože jsme již určili, že proměnná playerName bude String. Takže do něj nemůžeme uložit celé číslo.

Zajímavé články...