Swift - 常量



Swift 中的常量是什麼?

常量是指程式在其執行過程中可能不會更改的固定值。常量可以是任何資料型別,例如整數、浮點數、字元、雙精度數或字串字面量。也有列舉常量。它們與常規變數的處理方式相同,只是在定義後無法修改其值。

宣告 Swift 常量

常量用於儲存在整個程式執行過程中不會更改的值。它們總是在使用之前宣告,並且使用 `let` 關鍵字宣告。

語法

以下是常量的語法:

let number = 10

示例

Swift 程式演示如何宣告常量。

import Foundation

// Declaring constant
let constA = 42
print("Constant:", constA)

輸出

Constant: 42

如果我們嘗試為常量賦值,則會像下面的示例一樣出現錯誤:

import Foundation

// Declaring constant
let constA = 42
print("Constant:", constA)

// Assigning value to a constant
constA = 43
print("Constant:", constA)

輸出

main.swift:8:1: error: cannot assign to value: 'constA' is a 'let' constant
constA = 43
^~~~~~
main.swift:4:1: note: change 'let' to 'var' to make it mutable
let constA = 42
^~~
var

我們也可以在一行中宣告多個常量。其中每個常量都有其值,並用逗號分隔。

語法

以下是多個常量的語法:

let constantA = value, constantB = value, constantC = value

示例

Swift 程式演示如何在單行中宣告多個常量。

import Foundation

// Declaring multiple constants
let constA = 42, constB = 23, constC = 33
print("Constant 1:", constA)
print("Constant 2:", constB)
print("Constant 3:", constC)

輸出

Constant 1: 42
Constant 2: 23
Constant 3: 33

帶有常量的型別註釋

型別註釋用於在宣告時定義常量中應儲存的值的型別。在宣告常量時,我們可以透過在常量名稱後放置一個冒號,然後是型別來指定型別註釋。

如果我們在宣告常量時提供初始值,則很少使用型別註釋,因為 Swift 會根據賦值的值自動推斷常量的型別。

例如,`let myValue = "hello"`,因此 `myValue` 常量的型別為 String,因為我們將字串值賦給了該常量。

語法

以下是型別註釋的語法:

let constantName : Type = Value

示例

Swift 程式演示如何指定型別註釋。

import Foundation

// Declaring constant with type annotation
let myValue : String = "hello" 
print("Constant:", myValue)

輸出

Constant: hello

我們也可以在一行中定義多個相同型別的常量。其中每個常量名稱用逗號分隔。

語法

以下是多個常量的語法:

let constantA, constantB, constantC : Type

示例

Swift 程式演示如何在單型別註釋中指定多個常量。

import Foundation

// Declaring multiple constants in single-type annotation
let myValue1, myValue2, myValue3 : String 

// Assigning values 
myValue1 = "Hello"
myValue2 = "Tutorials"
myValue3 = "point"

print("Constant Value 1:", myValue1)
print("Constant Value 2:", myValue2)
print("Constant Value 3:", myValue3)

輸出

Constant Value 1: Hello
Constant Value 2: Tutorials
Constant Value 3: point

在 Swift 中命名常量

命名常量非常重要。它們應該具有唯一的名稱。不允許儲存兩個同名的常量,如果嘗試這樣做,則會出錯。Swift 提供以下常量命名規則:

  • 常量名稱可以包含任何字元,包括 Unicode 字元。例如,`let 你好 = “你好世界”`。

  • 常量名稱不應包含空格字元、數學符號、箭頭、私有 Unicode 標量值或線條和框繪製字元。

  • 常量名稱可以由字母、數字和下劃線字元組成。它必須以字母或下劃線開頭。例如,`let myValue = 34`。

  • 大小寫字母是不同的,因為 Swift 區分大小寫。例如,`let value` 和 `let Value` 是兩個不同的常量。

  • 常量名稱不應以數字開頭。

  • 不允許重新宣告同名的常量。或者不能更改為其他型別。

  • 不允許將常量更改為變數,反之亦然。

  • 如果要宣告與保留關鍵字相同的常量名稱,請在常量名稱前使用反引號 (`)。例如,`let `var` = “hello”`。

列印 Swift 常量

可以使用 `print()` 函式列印常量或變數的當前值。可以透過將名稱括在括號中並在開括號前使用反斜槓轉義來內插變數值。

示例

Swift 程式列印常量。

import Foundation

// Declaring constants
let constA = "Godzilla"
let constB = 1000.00

// Displaying constant
print("Value of \(constA) is more than \(constB) millions")

輸出

Value of Godzilla is more than 1000.0 millions
廣告