Бързи типове данни (с примери)

В този урок ще научите за различни типове данни, които езикът за програмиране Swift поддържа и ще го използвате, докато създавате променлива или константа.

Типът данни е типът данни (стойност), които променлива или константа могат да съхраняват в тях. Например в статията Swift Variables and Constants сте създали променлива и константа за съхраняване на низови данни в паметта.

Тези данни могат да бъдат текст / низ ("Здравейте") или число (12.45) или просто битове (0 и 1). Дефинирането на типа данни гарантира, че се съхранява само дефинираният тип данни.

Нека разгледаме сценарий:

Да предположим, че искате да създадете игра. Тъй като повечето игри показват висок резултат и име на играч след приключване на играта, трябва да съхраните тези две данни за вашата игра.

Най-големият резултат е число (например 59) и името на играча низ (например Джак). Можете да създадете две променливи или константи за съхраняване на данните.

В Swift това може да стане чрез деклариране на променливи и типа данни като:

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

Тук декларирахме променлива highScore от тип, Intкоято съхранява стойност 59. И променлива playerName от тип, Stringкоято съхранява стойността Jack.

Ако обаче направите нещо подобно:

 var highScore: Int = "Jack"

Ще получите грешка във времето на компилация, като не можете да конвертирате стойност от тип „String“ в определен тип „Int“ .

Това е така, защото сте декларирали highScore за съхраняване на цяло число, но сте поставили низ в него. Тази грешка гарантира, че highScore може да съхранява само номер, но не и името на играча.

Размер на тип данни

Друга важна част от типа данни е неговият размер. Това определя размера на данните, които могат да се съхраняват в дадена променлива или константа.

А Тип на размер се измерва по отношение на бита и може да съхранява стойности до запълването 2 бита . Ако не знаете за Bit, помислете за него като за стойност, която е 0 или 1.

Така че, за Type size = 1 бит, той може да съхранява само upto, 2 1 = 2, две стойности: или 0 или 1. Така че 1 битова система за програма за букви може да тълкува 0 като a / 0 и 1 като b / 1.0.

 0 -> a или 0 1 -> b или 1

По същия начин двубитова система може да съхранява до 2 2 = 4 стойности: (00,01,10,11) и всяка комбинация може да бъде представена като:

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

За битова система тя може да съхранява в нея максимум 2 n стойности.

Бързи типове данни

По-долу са изброени най-често използваните типове данни:

Bool

  • Променлива / константа, декларирана от тип Bool, може да съхранява само две стойности trueили false.
  • Стойност по подразбиране : false
  • Често се използва, когато работите с if-elseизраз. Суифт, ако иначе статия обхваща подробно за това.

Пример 1: Булев тип данни

 let result:Bool = true print(result)

Когато стартирате програмата, изходът ще бъде:

 вярно

Цяло число

  • Variable/Constant declared of integer type can store whole numbers both positive and negative including zero with no fractional components .
  • Default Value: 0
  • Size: 32/64 bit depends on the platform type.
  • Range: -2,147,483,648 to 2,147,483,647 (32 bit platform)
    -9223372036854775808 to 9223372036854775807 (64 bit platform
  • There are many variants of Integer type.e.g. UInt, Int8, Int16 etc. The most common one you use is of Int.
  • If you have a requirement to specify the size/type of integer a variable/constant can hold, you can store it more specifically using UInt, Int8, Int16 etc. which we are going to explore below.

Example 2: Integer data type

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

When you run the program, the output will be:

 100 -100 

В горния пример декларирахме променлива highScore от тип Int. Първо, ние го присвоихме със стойност 100, така че print(highScore)извежда 100 на екрана.

По-късно променихме стойността на -100, използвайки оператора за присвояване highScore = -100, print(highScore)извежда -100 на екрана.

Нека разгледаме някои варианти на Intтипа в Swift.

Int8

  • Вариант от тип Integer, който може да съхранява както положителни, така и отрицателни малки числа.
  • Стойност по подразбиране : 0
  • Размер : 8 бита
  • Обхват : -128 до 127

Цяло Int8число може да съхранява общо 2 8 = (256) стойности в него. т.е. може да съхранява числа от 0 до 255 нали?

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: Swift е безопасен за типа език

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

Горният код ще създаде грешка, защото вече посочихме, че променливата playerName ще бъде низ. Така че не можем да съхраняваме цяло число в него.

Интересни статии...