Swift - 可選值(Optionals)



Swift 引入了一種名為可選型別的新特性。可選型別處理可能不存在或未定義的值。它允許變量表示一個值或 nil。可選值類似於在 Objective-C 中使用 nil 指標,但它們適用於任何型別,而不僅僅是類。要指定可選型別,必須在型別名稱後使用問號 (?)。

語法

以下是可選變數的語法:

var perhapsInt: Int?

示例

Swift 程式演示如何建立可選變數。

// Declaring an optional Integer
var number: Int?

// Assigning a value to the optional
number = 34

// Using optional binding to safely unwrap its value
if let x = number {
   print("Value is \(x)!")
} else {
   print("Value is unknown")
}

輸出

Value is 34!

帶有 nil 的可選值

如果要將可選變數指定為無值狀態或沒有值,則可以為該變數賦值 **nil**。或者,如果未為可選變數賦值,則 Swift 會自動將該變數的值設定為 nil。在 Swift 中,只允許將 nil 賦值給可選變數,如果嘗試將 nil 賦值給非可選變數或常量,則會報錯。

語法

以下是將可選值賦值為 nil 的語法:

var perhapsStr: Int?  = nil

示例

Swift 程式演示如何將 nil 賦值給可選變數。

// Optional variable
var num: Int? = 42

// Setting variable to nil 
num = nil

// Check if the optional has a value or not
if num != nil {
   print("Optional has a value: \(num!)")
} else {
   print("Optional is nil.")
}

輸出

Optional is nil.

強制展開

如果將變數定義為 **可選** 型別,則要獲取此變數的值,必須對其進行展開。因此,要 **展開** 值,必須在變數末尾新增感嘆號 (!) 。這告訴編譯器您確定可選值包含某個值。

語法

以下是強制展開的語法:

let variableName = optionalValue!

示例

Swift 程式演示如何展開可選值。

// Declaring an optional Integer
var number: Int?

// Assigning a value to the optional
number = 34

// Using exclamation mark (!) to forcefully unwrapping the optional
let value: Int = number!

// Displaying the unwrapped value
print(value)

輸出

34

隱式展開可選值

可以使用感嘆號 (!) 而不是問號 (?) 來宣告可選變數。此類可選變數將自動展開,無需在變數末尾使用任何其他感嘆號 (!) 來獲取已賦值的值。

示例

import Cocoa

var myString:String!
myString = "Hello, Swift 4!"

if myString != nil {
   print(myString)
}else{
   print("myString has nil value")
}

輸出

Hello, Swift 4!

可選繫結

使用可選繫結來確定可選值是否包含值,如果包含,則將其值作為臨時常量或變數使用。或者可以說,可選繫結允許我們展開和使用可選值中存在的值。它可以防止我們展開 nil 值並導致執行時崩潰。

可以使用 if let、guard 和 while 語句執行可選繫結。允許在一個 if 語句中使用多個可選繫結和布林條件,用逗號分隔。如果給定的多個可選繫結和布林條件中的任何一個為 nil,則整個 if 語句都被認為是 false。

語法

以下是可選繫結的語法:

if let constantName = someOptional, let variableName = someOptional {
   statements
}

示例

// Declaring an optional Integer
var number: Int?

// Assigning a value to the optional
number = 50

// Using optional binding to safely unwrap the optional
if let x = number {
   print("Number is \(x)!")
} else {
   print("Number is unknown")
}

輸出

Number is 50!

空合併運算子 (??)

在 Swift 中,還可以使用空合併運算子 (??) 來處理缺失值,並在可選值為 nil 時提供預設值。它是使用可選繫結和預設值的簡寫方法。

語法

以下是空合併運算子的語法:

Let output = optionalValue ?? defaultValue

空合併運算子 (??) 檢查左側運算元的值是否不為 nil。如果它不為 nil,則展開該值。如果該值為 nil,則它將提供右側運算元中的值(或作為備用值)。

示例

// Function to fetch employee salary
func getEmpSalary() -> Int? {

   // Return nil when salary is not available
   return nil
}

// Using the nil-coalescing operator to provide a valid salary
let salary = getEmpSalary() ?? 5000 

// Displaying the result
print("Salary: \(salary)")

輸出

Salary: 5000
廣告