Hitre vrste podatkov (s primeri)

V tej vadnici boste spoznali različne vrste podatkov, ki jih podpira programski jezik Swift, in jih uporabljali med ustvarjanjem spremenljivke ali konstante.

Podatkovni tip je vrsta podatkov (vrednosti), ki jih lahko shrani spremenljivka ali konstanta. V članku Swift Variables and Constants ste na primer ustvarili spremenljivko in konstanto za shranjevanje nizovnih podatkov v pomnilnik.

Ti podatki so lahko besedilo / niz ("Pozdravljeni") ali številka (12.45) ali samo bit (0 in 1). Določitev podatkovnega tipa zagotavlja, da se shrani samo določena vrsta podatkov.

Oglejmo si scenarij:

Recimo, da želite ustvariti igro. Ker večina iger po zaključku igre prikazuje visok rezultat in ime igralca, morate ta dva podatka shraniti za igro.

Najboljši rezultat je število (npr. 59) in ime igralca niz (npr. Jack). Za shranjevanje podatkov lahko ustvarite dve spremenljivki ali konstanti.

V Swiftu je to mogoče storiti z deklariranjem spremenljivk in podatkovnega tipa kot:

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

Tu smo razglasili spremenljivko highScore tipa, Intki shranjuje vrednost 59. In spremenljivko playerName tipa, Stringki hrani vrednost Jack.

Če pa naredite kaj takega:

 var highScore: Int = "Jack"

Dobili boste napako časa prevajanja, v kateri ni mogoče pretvoriti vrednosti tipa 'String' v določen tip 'Int' .

To je zato, ker ste razglasili highScore za shranjevanje celoštevilčne vrednosti, vendar ste vanj postavili niz. Ta napaka zagotavlja, da lahko HighScore shrani samo številko in ne imena igralca.

Velikost vrste podatkov

Drug pomemben del podatkovnega tipa je njegova velikost. To določa velikost podatkov, ki jih je mogoče shraniti v dani spremenljivki ali konstanti.

A tip je velikost se meri glede na malo in lahko shranite vrednosti upto 2 bitov . Če ne veste za Bit, si omislite vrednost kot 0 ali 1.

Torej, za velikost Type = 1 bit lahko shrani samo do, 2 1 = 2, dve vrednosti: bodisi 0 bodisi 1. Torej lahko 1-bitni sistem za črkovni program 0 razlaga kot a / 0 in 1 kot b / 1.0.

 0 -> a ali 0 1 -> b ali 1

Prav tako lahko dvobitni sistem shrani do 2 2 = 4 vrednosti: (00,01,10,11) in vsako kombinacijo lahko predstavimo kot:

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

Za bitni sistem lahko vanjo shrani največ 2 n vrednosti.

Hitre vrste podatkov

Spodaj so navedeni najpogostejši tipi podatkov, ki se uporabljajo v hitrem postopku:

Bool

  • Spremenljivka / konstanta, deklarirana za tip Bool, lahko shrani samo dve vrednosti trueali false.
  • Privzeta vrednost : false
  • Pogosto se uporablja pri delu z if-elseizjavo. Članek o hitrem, če drugače podrobno opisuje to.

Primer 1: logična vrsta podatkov

 let result:Bool = true print(result)

Ko zaženete program, bo rezultat:

 prav

Celo število

  • Spremenljivka / konstanta, deklarirana za celo število, lahko shrani celotna števila tako pozitivnih kot negativnih, vključno z ničlo, brez delnih komponent.
  • Privzeta vrednost : 0
  • Velikost : 32/64 bit je odvisna od vrste platforme.
  • Razpon : -2,147,483,648 do 2,147,483,647 (32-bitna platforma)
    -9223372036854775808 do 9223372036854775807 (64-bitna platforma
  • Obstaja veliko različic Integer type.eg UInt, Int8, Int16itd Najpogostejši ki ga uporabljate je Int.
  • Če imate zahteva, da določite velikost / tip celo spremenljivka / konstanta lahko drži, lahko shranite bolj specifično uporabo UInt, Int8, Int16itd, ki bomo raziskati spodaj.

2. primer: celoštevilčni podatkovni tip

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

Ko zaženete program, bo rezultat:

 100 -100 

V zgornjem primeru smo razglasili spremenljivko highScore tipa Int. Najprej smo mu dodelili vrednost 100, tako da print(highScore)na zaslon prikaže 100.

Kasneje smo vrednost spremenili na -100 z uporabo operatorja dodelitve, tako highScore = -100da print(highScore)na zaslon prikaže -100.

Oglejmo si nekaj različic Intvrste v Swiftu.

Int8

  • Varianta tipa Integer, ki lahko shranjuje pozitivna in negativna majhna števila.
  • Privzeta vrednost : 0
  • Velikost : 8 bit
  • Razpon : -128 do 127

Celo Int8število lahko vanj shrani 2 8 = (256) vrednosti. torej lahko shrani številke od 0 do 255 kajne?

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.

Primer 10: Swift je jezik, ki je varen za tip

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

Zgornja koda bo ustvarila napako, ker smo že določili, da bo spremenljivka playerName String. V njej torej ne moremo shraniti celoštevilčne številke.

Zanimive Članki...