Jenis Data Swift (Dengan Contoh)

Dalam tutorial ini, anda akan belajar mengenai pelbagai jenis data yang disokong oleh bahasa pengaturcaraan Swift dan menggunakannya semasa membuat pemboleh ubah atau pemalar.

Jenis data adalah jenis data (nilai) yang boleh disimpan oleh pemboleh ubah atau pemalar di dalamnya. Sebagai contoh, dalam artikel Swift Variables and Constants, anda membuat pemboleh ubah dan pemalar untuk menyimpan data rentetan dalam memori.

Data ini boleh berupa teks / rentetan ("Hello") atau angka (12.45) atau hanya bit (0 & 1). Mendefinisikan jenis data memastikan hanya jenis data yang ditentukan disimpan.

Mari lihat senario:

Katakan anda mahu membuat permainan. Oleh kerana, kebanyakan permainan memaparkan skor tinggi dan nama pemain setelah permainan selesai, anda perlu menyimpan dua data ini untuk permainan anda.

Skor tinggi adalah nombor (misalnya 59) dan nama pemain rentetan (contohnya Jack). Anda boleh membuat dua pemboleh ubah atau pemalar untuk menyimpan data.

Di Swift, ini dapat dilakukan dengan menyatakan pemboleh ubah dan jenis data sebagai:

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

Di sini, kami menyatakan pemboleh ubah highScore dari jenis Intyang menyimpan nilai 59. Dan, variabel playerName jenis Stringyang menyimpan nilai Jack.

Walau bagaimanapun, jika anda melakukan perkara seperti ini:

 Var highScore: Int = "Jack"

Anda akan mendapat ralat masa kompilasi yang menyatakan tidak dapat menukar nilai jenis 'String' ke jenis 'Int' yang ditentukan .

Ini kerana anda menyatakan nilai tinggi untuk menyimpan nilai integer tetapi meletakkan rentetan di dalamnya. Kesalahan ini memastikan highScore hanya dapat menyimpan nombor dan bukan nama pemain.

Ukuran Jenis Data

Bahagian penting lain dari jenis data adalah ukurannya. Ini menentukan ukuran data yang dapat disimpan dalam pemboleh ubah atau pemalar tertentu.

A Type saiz diukur dari segi bit dan boleh menyimpan nilai hamper 2 bit . Sekiranya anda tidak mengetahui mengenai Bit, anggap ia sebagai nilai yang 0 atau 1.

Jadi, untuk ukuran Jenis = 1 bit, ia hanya dapat menyimpan sehingga, 2 1 = 2, dua nilai: sama ada 0 atau 1. Jadi sistem 1 bit untuk program huruf dapat menafsirkan 0 sebagai a / 0 dan 1 sebagai b / 1.0.

 0 -> a atau 0 1 -> b atau 1

Begitu juga, sistem dua bit dapat menyimpan hingga 2 2 = 4 nilai: (00,01,10,11) dan setiap kombinasi dapat ditunjukkan sebagai:

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

Untuk sistem bit, ia boleh menyimpan maksimum 2 n nilai di dalamnya.

Jenis Data Swift

Jenis data yang paling biasa digunakan dalam pantas disenaraikan di bawah:

Bool

  • Pemboleh ubah / Pemalar yang dinyatakan dari jenis Bool boleh menyimpan hanya dua nilai sama ada trueatau false.
  • Nilai Lalai : salah
  • Ia sering digunakan semasa anda bekerja dengan if-elsepenyataan. Artikel pantas jika ada merangkumi secara terperinci mengenainya.

Contoh 1: Jenis data Boolean

 let result:Bool = true print(result)

Semasa anda menjalankan program, outputnya adalah:

 benar

Bilangan bulat

  • Pemboleh ubah / Pemalar yang dinyatakan jenis integer dapat menyimpan nombor bulat baik positif dan negatif termasuk sifar tanpa komponen pecahan.
  • Nilai Lalai : 0
  • Saiz : 32/64 bit bergantung pada jenis platform.
  • Julat : -2,147,483,648 hingga 2,147,483,647 (platform 32 bit)
    -9223372036854775808 hingga 9223372036854775807 (platform 64 bit
  • Terdapat banyak varian Integer type.eg UInt, Int8, Int16dan lain-lain Yang paling biasa anda gunakan adalah daripada Int.
  • Jika anda mempunyai keperluan untuk menentukan saiz / jenis integer pembolehubah / pemalar boleh memegang, anda boleh menyimpannya lebih khusus menggunakan UInt, Int8, Int16dan lain-lain yang kita akan meneroka di bawah.

Contoh 2: Jenis data integer

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

Semasa anda menjalankan program, outputnya adalah:

 100 -100 

Dalam contoh di atas kita menyatakan jenis skor tinggi berubah Int. Pertama, kami menetapkannya dengan nilai 100 sehingga print(highScore)output 100 di skrin.

Kemudian, kami menukar nilai menjadi -100 menggunakan operator tugasan highScore = -100, print(highScore)output -100 di skrin.

Mari kita terokai beberapa varian Intjenis di Swift.

Int8

  • Varian jenis Integer yang dapat menyimpan nombor kecil positif dan negatif.
  • Nilai Lalai : 0
  • Saiz : 8 bit
  • Julat : -128 hingga 127

Bilangan Int8bulat dapat menyimpan sama sekali 2 8 = (256) nilai di dalamnya. iaitu boleh menyimpan nombor dari 0 hingga 255 kan?

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.

Contoh 10: Swift adalah bahasa selamat jenis

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

Kod di atas akan membuat ralat kerana kita sudah menentukan bahawa pemboleh ubah nama pemain akan menjadi Rentetan. Oleh itu, kita tidak dapat menyimpan nombor Integer di dalamnya.

Artikel menarik...