Greiti duomenų tipai (su pavyzdžiais)

Šioje pamokoje sužinosite apie įvairius duomenų tipus, kuriuos palaiko „Swift“ programavimo kalba, ir naudosite juos kurdami kintamąjį ar konstantą.

Duomenų tipas yra duomenų (reikšmės) tipas, kurį kintamasis ar konstanta gali jame laikyti. Pavyzdžiui, straipsnyje „Greiti kintamieji ir konstantos“ sukūrėte kintamąjį ir konstantą, kad atmintyje būtų saugomi eilutės duomenys.

Šie duomenys gali būti tekstas / eilutė („Labas“) arba skaičius (12,45) arba tik bitai (0 ir 1). Apibrėžiant duomenų tipą užtikrinama, kad būtų saugomi tik apibrėžti duomenų tipai.

Pažvelkime į scenarijų:

Tarkime, kad norite sukurti žaidimą. Kadangi dauguma žaidimų rodo aukštą rezultatą ir žaidėjo vardą pasibaigus žaidimui, turite išsaugoti šiuos du savo žaidimo duomenis.

Aukščiausias rezultatas yra skaičius (pvz., 59) ir žaidėjo vardas - eilutė (pvz., Jackas). Duomenims saugoti galite sukurti du kintamuosius arba konstantas.

„Swift“ tai galima padaryti deklaruojant kintamuosius ir duomenų tipą:

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

Čia mes paskelbėme „highScore“ tipo kintamąjį, Intkuriame saugoma 59 reikšmė. Ir „playerName“ tipo kintamasis, Stringkuriame saugoma vertė Jack.

Tačiau jei darote ką nors panašaus:

 aukščiausias rezultatas: Int = "Džekas"

Gausite kompiliavimo laiko klaidą, nurodydami, kad negalima konvertuoti tipo „String“ vertės į nurodytą tipą „Int“ .

Taip yra todėl, kad jūs paskelbėte „HighScore“, kad išsaugotumėte sveiko skaičiaus vertę, bet įdėjote eilutę. Ši klaida užtikrina, kad „HighScore“ gali išsaugoti tik numerį, o ne žaidėjo vardą.

Duomenų tipo dydis

Kita svarbi duomenų tipo dalis yra jų dydis. Tai nurodo duomenų, kuriuos galima saugoti tam tikrame kintamajame ar konstantoje, dydį.

A tipo anketa dydis matuojamas tiek ir gali saugoti vertybes net iki 2 bitai . Jei nežinote apie „Bit“, galvokite apie tai kaip apie 0 arba 1.

Taigi, jei tipas yra = 1 bitas, jis gali išsaugoti tik iki 2, 1 = 2, dvi reikšmes: 0 arba 1. Taigi 1 bitų sistema raidžių programai gali interpretuoti 0 kaip a / 0 ir 1 kaip b / 1.0.

 0 -> a arba 0 1 -> b arba 1

Panašiai dviejų bitų sistema gali išsaugoti iki 2 2 = 4 reikšmių: (00,01,10,11) ir kiekvieną derinį galima pateikti kaip:

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

Bitų sistemoje joje galima išsaugoti ne daugiau kaip 2 n reikšmes.

Greiti duomenų tipai

Dažniausiai greitai naudojami duomenų tipai yra išvardyti toliau:

Bool

  • „Bool“ tipo kintamasis / pastovus deklaruotas gali išsaugoti tik dvi reikšmes truearba false.
  • Numatytoji reikšmė : klaidinga
  • Jis dažnai naudojamas, kai dirbate su if-elseteiginiu. Greitas, jei kitame straipsnyje išsamiai aprašytas.

1 pavyzdys: Bulio logikos duomenų tipas

 let result:Bool = true print(result)

Kai paleisite programą, išvestis bus:

 tiesa

Sveikasis skaičius

  • Kintamasis / nuolatinis sveikojo skaičiaus tipo skaičius gali įrašyti sveikus skaičius ir teigiamą, ir neigiamą, įskaitant nulį, be dalinių komponentų.
  • Numatytoji vertė : 0
  • Dydis : 32/64 bitai priklauso nuo platformos tipo.
  • Diapazonas : nuo 2 147 483 648 iki 2 147 483 647 (32 bitų platforma)
    -9223372036854775808 iki 9223372036854775807 (64 bitų platforma)
  • Yra daug variantų Integer type.eg UInt, Int8, Int16ir tt Dažniausiai vienas jūs naudojate yra Int.
  • Jei turite reikalavimas nurodyti dydis / tipas sveikasis skaičius kintamas / konstanta gali turėti, jūs galite laikyti jį konkrečiau naudojant UInt, Int8, Int16ir tt, kurie mes ketiname ištirti žemiau.

2 pavyzdys: sveikųjų duomenų tipas

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

Kai paleisite programą, išvestis bus:

 100–100 

Ankstesniame pavyzdyje mes paskelbėme kintamą tipą „HighScore“ Int. Pirma, mes priskyrėme jį 100 vertei, taigi print(highScore)ekrane išvedama 100.

Vėliau, naudodami priskyrimo operatorių, pakeitėme vertę į -100 highScore = -100, print(highScore)ekrane pateikiame -100.

Panagrinėkime keletą Int„Swift“ tipo variantų .

Int8

  • Sveiko skaičiaus variantas, į kurį galima įrašyti tiek teigiamus, tiek neigiamus mažus skaičius.
  • Numatytoji vertė : 0
  • Dydis : 8 bitų
  • Diapazonas : nuo -128 iki 127

Int8Sveikas skaičius gali laikyti iš viso 2 8 = (256) vertes, į jį. ty jis gali saugoti skaičius nuo 0 iki 255, tiesa?

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 pavyzdys: „Swift“ yra saugi tipo kalba

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

Pirmiau pateiktas kodas sukurs klaidą, nes mes jau nurodėme, kad kintamasis playerName bus eilutė. Taigi negalime jame laikyti sveikojo skaičiaus.

Įdomios straipsniai...