Ātri datu tipi (ar piemēriem)

Šajā apmācībā jūs uzzināsit par dažādiem datu tipiem, kurus atbalsta Swift programmēšanas valoda, un izmantosiet tos, veidojot mainīgo vai konstanti.

Datu tips ir datu veids (vērtība), ko mainīgais vai konstante var tajā uzglabāt. Piemēram, rakstā Swift Variables and Constants jūs izveidojāt mainīgo un konstanti virknes datu glabāšanai atmiņā.

Šie dati var būt teksts / virkne ("Labdien") vai skaitlis (12,45) vai vienkārši biti (0 un 1). Datu veida definēšana nodrošina tikai definētā veida datu saglabāšanu.

Apskatīsim scenāriju:

Pieņemsim, ka vēlaties izveidot spēli. Tā kā lielākajai daļai spēļu pēc spēles pabeigšanas tiek rādīts augsts rezultāts un spēlētāja vārds, šie divi spēles dati jums ir jāsaglabā.

Augstākais rezultāts ir skaitlis (piemēram, 59) un spēlētāja vārds virkne (piemēram, Džeks). Datu glabāšanai varat izveidot divus mainīgos vai konstantes.

Programmā Swift to var izdarīt, deklarējot mainīgos un datu tipu kā:

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

Šeit mēs paziņojām par tipa IntHighScore mainīgo, kas glabā vērtību 59. Un, playerName tipa mainīgais, Stringkas glabā vērtību Jack.

Tomēr, ja jūs darāt kaut ko līdzīgu šim:

 var highScore: Int = "Džeks"

Jūs saņemsiet kompilēšanas laika kļūdu, norādot , ka veida “String” vērtību nevar pārveidot par norādīto tipu “Int” .

Tas ir tāpēc, ka jūs paziņojāt par labāko rezultātu, lai saglabātu veselu skaitli, bet tajā ievietojāt virkni. Šī kļūda nodrošina to, ka rekordā var saglabāt tikai numuru, nevis spēlētāja vārdu.

Datu veida lielums

Vēl viena svarīga datu tipa daļa ir tā lielums. Tas norāda datu lielumu, ko var saglabāt noteiktā mainīgajā vai konstante.

A Type s lielums tiek mērīts ziņā bitu un var uzglabāt vērtības līdz pat 2 bitiem . Ja jūs nezināt par Bit, domājiet par to kā vērtību, kas ir vai nu 0, vai 1.

Tātad tipa lielums = 1 bits gadījumā tas var saglabāt tikai upto, 2 1 = 2, divas vērtības: vai nu 0, vai 1. Tātad burtu programmas 1 bitu sistēma var interpretēt 0 kā a / 0 un 1 kā b / 1.0.

 0 -> a vai 0 1 -> b vai 1

Tāpat divu bitu sistēma var saglabāt līdz pat 2 2 = 4 vērtībām: (00,01,10,11), un katru kombināciju var attēlot kā:

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

Bitu sistēmai tajā var saglabāt ne vairāk kā 2 n vērtības.

Ātri datu tipi

Tālāk ir uzskaitīti visbiežāk izmantotie datu tipi, kas tiek izmantoti ātri.

Bool

  • Mainīgais / Pastāvīga deklarētais bool tipa var saglabāt tikai divas vērtības, vai nu truevai false.
  • Noklusējuma vērtība : false
  • To bieži lieto, strādājot ar if-elsepaziņojumu. Ātri, ja citādi raksts sīki apraksta par to.

1. piemērs: Būla datu tips

 let result:Bool = true print(result)

Palaidot programmu, izeja būs:

 taisnība

Vesels skaitlis

  • Mainīgais / konstants, kas deklarēts kā vesels skaitlis, var saglabāt veselus skaitļus gan pozitīvos, gan negatīvos, ieskaitot nulli, bez daļskaitļiem.
  • Noklusējuma vērtība : 0
  • Izmērs : 32/64 biti ir atkarīgi no platformas veida.
  • Diapazons : no 2 147 483 648 līdz 2 147 483 647 (32 bitu platforma)
    -9223372036854775808 līdz 9223372036854775807 (64 bitu platforma)
  • Ir daudzi varianti Integer type.eg UInt, Int8, Int16uc Visbiežākais jūs izmantojat ir Int.
  • Ja jums ir prasība, lai norādītu uz skaitlim mainīga / nemainīga, var turēt izmēru / veidu, jūs varat uzglabāt to precīzāk izmantot UInt, Int8, Int16uc, ko mēs gatavojamies, lai izpētītu zemāk.

2. piemērs: veselais datu tips

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

Palaidot programmu, izeja būs:

 100 -100 

Iepriekš minētajā piemērā mēs paziņojām par mainīgu tipa HighScore Int. Pirmkārt, mēs to piešķīrām ar vērtību 100, tāpēc print(highScore)ekrānā tiek parādīti 100.

Vēlāk tika mainīta vērtību -100 izmantojot piešķires operators, kā highScore = -100tā, print(highScore)izejas -100 ekrānā.

Izpētīsim dažus veida variantus IntSwift.

Int8

  • Integer tipa variants, kurā var saglabāt gan pozitīvus, gan negatīvus mazus skaitļus.
  • Noklusējuma vērtība : 0
  • Izmērs : 8 biti
  • Diapazons : -128 līdz 127

Int8Vesels skaitlis var uzglabāt kopā 2 8 = (256) vērtības tajā. ti, tas var saglabāt skaitļus no 0 līdz 255, vai ne?

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.

10. piemērs: Swift ir tipam droša valoda

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

Iepriekš minētais kods radīs kļūdu, jo mēs jau norādījām, ka mainīgais playerName būs virkne. Tāpēc mēs nevaram tajā saglabāt veselu skaitli.

Interesanti raksti...