Swift-tietotyypit (esimerkkien kanssa)

Tässä opetusohjelmassa opit erilaisista tietotyypeistä, joita Swift-ohjelmointikieli tukee, ja käyttämään sitä samalla, kun luot muuttujan tai vakion.

Tietotyyppi on tietotyyppi (arvo), jonka muuttuja tai vakio voi tallentaa siihen. Esimerkiksi artikkelissa Swift Variables and Constants, olet luonut muuttujan ja vakion merkkijonodatan tallentamiseksi muistiin.

Nämä tiedot voivat olla teksti / merkkijono ("Hei") tai numero (12.45) tai vain bittiä (0 & 1). Tietotyypin määrittäminen varmistaa, että vain määritelty tietotyyppi tallennetaan.

Katsotaanpa skenaariota:

Oletetaan, että haluat luoda pelin. Koska useimmilla peleillä on korkeat pisteet ja pelaajan nimi pelin päättymisen jälkeen, sinun on tallennettava nämä kaksi dataa pelillesi.

Korkeat pisteet ovat numero (esim. 59) ja pelaajan nimi merkkijono (esim. Jack). Voit luoda kaksi muuttujaa tai vakiota tietojen tallentamiseksi.

Swiftissä tämä voidaan tehdä ilmoittamalla muuttujat ja tietotyyppi seuraavasti:

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

Tässä julistettiin tyypin highScore muuttuja, Intjoka tallentaa arvon 59. Ja, playerName-tyypin muuttuja, Stringjoka tallentaa arvon Jack.

Jos kuitenkin teet jotain tällaista:

 var highScore: Int = "Jack"

Saat käännösaikavirheen , jonka mukaan String-tyypin arvoa ei voida muuntaa määritetyksi tyypiksi Int .

Tämä johtuu siitä, että ilmoitit ennätyksen tallentaa kokonaislukuarvon, mutta asetit merkkijonon siihen. Tämä virhe varmistaa, että huipputulos voi tallentaa vain numeron eikä pelaajan nimeä.

Tietotyypin koko

Toinen tärkeä osa tietotyyppiä on sen koko. Tämä määrittää tietomuuttujaan tai vakioon tallennettavan tiedon koon.

Tyyppi: n koko on mitataan bitin ja voi tallentaa arvot Jopa 2 bittiä . Jos et tiedä Bitistä, ajattele sitä arvona, joka on joko 0 tai 1.

Joten tyypin koko = 1 bitti, se voi tallentaa vain upto, 2 1 = 2, kaksi arvoa: joko 0 tai 1. Joten 1-bittinen järjestelmä kirjainohjelmalle voi tulkita 0 a / 0: ksi ja 1 b: ksi / 1.0.

 0 -> a tai 0 1 -> b tai 1

Samoin kaksibittinen järjestelmä voi tallentaa jopa 2 2 = 4 arvoa: (00,01,10,11) ja kukin yhdistelmä voidaan esittää seuraavasti:

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

Bittijärjestelmää varten se voi tallentaa siihen enintään 2 n arvoa.

Nopeat tietotyypit

Seuraavassa luetellaan yleisimmät nopeassa käytössä olevat tietotyypit:

Bool

  • Bool-tyypin muuttuja / vakio ilmoitettu voi tallentaa vain kaksi arvoa joko truetai false.
  • Oletusarvo : false
  • Sitä käytetään usein, kun työskentelet if-elselausunnon kanssa. Nopea, jos muuten artikkeli kattaa yksityiskohtaisesti siitä.

Esimerkki 1: Boolen tietotyyppi

 let result:Bool = true print(result)

Kun suoritat ohjelmaa, tulos on:

 totta

Kokonaisluku

  • Muuttuja / vakio, joka ilmoitetaan kokonaislukutyypillä, voi tallentaa kokonaislukuja sekä positiivisina että negatiivisina, mukaan lukien nolla ilman murto-osia.
  • Oletusarvo : 0
  • Koko : 32/64 bittiä riippuu alustan tyypistä.
  • Alue : -2,147,483,648-2,147,483,647 (32-bittinen alusta)
    -9223372036854775808 - 9223372036854775807 (64-bittinen alusta)
  • On olemassa monia muunnelmia Integer type.eg UInt, Int8, Int16jne Yleisin käytät on Int.
  • Jos sinulla on vaatimus määrittää koko / tyyppi kokonaisluku muuttujan / vakio mahtuu, voit tallentaa sen tarkemmin käyttämällä UInt, Int8, Int16jne jota aiomme tutkia alla.

Esimerkki 2: Kokonaislukutietotyyppi

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

Kun suoritat ohjelmaa, tulos on:

 100-100 

Yllä olevassa esimerkissä ilmoitimme tyypin muuttujan huippupisteet Int. Ensinnäkin annoimme sen arvolla 100, joten se print(highScore)antaa näytölle 100.

Myöhemmin muutimme arvoksi -100 käyttämällä tehtävänoperaattoria sellaisenaan highScore = -100, print(highScore)antaa näytölle -100.

Tutkitaan joitain Inttyypin muunnelmia Swiftissä.

Int8

  • Kokonaisluvun tyyppi, joka voi tallentaa sekä positiivisia että negatiivisia pieniä lukuja.
  • Oletusarvo : 0
  • Koko : 8 bittiä
  • Alue : -128 - 127

Int8Kokonaisluku voidaan tallentaa yhteensä 2 8 = (256) -arvoja. ts. se voi tallentaa numeroita 0-255, eikö?

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.

Esimerkki 10: Swift on tyypiltään turvallinen kieli

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

Yllä oleva koodi luo virheen, koska olemme jo määrittäneet, että muuttuja playerName tulee olemaan merkkijono. Joten emme voi tallentaa kokonaislukua siihen.

Mielenkiintoisia artikkeleita...