Swift - 型別轉換



什麼是 Swift 中的型別轉換?

型別轉換是 Swift 中的一項特殊功能,用於檢查例項的型別或將類、結構體或列舉的例項型別更改為另一個類、結構體或列舉。它非常重要,因為它允許在執行時進行型別檢查,並安全地將例項向下轉換為子類型別。

Swift 支援兩個運算子:is 和 as。‘is’ 運算子用於檢查值的型別,而 ‘as’ 用於將型別值轉換為不同的型別。型別轉換還檢查例項型別是否遵循特定的協議一致性標準。

Swift 支援兩種型別的型別轉換:

  • 向上轉型
  • 向下轉型

Swift 中的向上轉型

將子類例項轉換為其基類型別的過程稱為向上轉型。或者我們可以說,向上轉型是一個將派生類例項視為其基類例項的過程。藉助向上轉型,我們只能呼叫超類的方法和屬性。向上轉型後,我們不允許直接呼叫子類的方法或屬性,如果嘗試這樣做,將會出現錯誤。

在 Swift 中,向上轉型是隱式的,這意味著我們不需要任何特殊的語法來進行向上轉型,我們可以直接將子類例項轉換為超類例項。直接使用它是安全的,因為子類例項始終被視為超類例項。向上轉型通常在我們處理多型程式碼或希望將不同型別的例項視為其公共基類例項時使用。

示例

Swift 程式,用於將子類例項向上轉型為超類例項。

// Base class
class Shape {
   func display(){
      print("Ball is in the shape of sphere")
   }
}

// Sub class
class Rectangle: Shape {
   func show(){
      print("Rectangle is the most commonly used shape")
   }
}

// Creating an instance of the Rectangle class
let rect = Rectangle()

// Upcasting the instance of the rectangle class as the instance of the Shape class
let obj : Shape = rect

// Accessing the method of superclass
obj.display()

// Now we are not able to directly access the method or properties of the sub-class
// If we do we will get an error
// obj.show()

輸出

它將產生以下輸出:

Ball is in the shape of sphere

Swift 中的向下轉型

將超類型別例項轉換為子類型別的過程稱為向下轉型。或者我們可以說,向下轉型是一個將基類例項視為派生類例項的過程。向下轉型不一定會成功,它也可能失敗。Swift 支援兩種型別的向下轉型:

  • 條件向下轉型 (as?)
  • 強制向下轉型 (as!)

讓我們詳細討論這兩種型別。

條件向下轉型 (as?)

條件向下轉型 (as?) 運算子用於將超類型別例項向下轉換為特定的子類型別。當向下轉型成功時,此運算子將返回包含子類例項的可選值。當向下轉型不成功時,此運算子將返回 nil。此運算子通常在我們不確定向下轉型是否會成功時使用。

語法

以下是條件向下轉型運算子 (as?) 的語法:

if let constName = instance as? Type {
   // Statement that will execute when downcast is successful
} else {
   // Statement that will execute when downcast is unsuccessful
}

示例

Swift 程式,演示如何使用條件向下轉型運算子 (as?)。

// Base Class
class ProgrammingLanguage {
   func show() {
      print("Welcome to the great world of learning")
   }
}

// Subclass
class Swift: ProgrammingLanguage {
   func display() {
      print("Welcome to Swift tutorial")
   }
}
let obj: ProgrammingLanguage = Swift()

// Here the conditional downcasting will be successful
if let result1 = obj as? Swift {
   print("Downcast is successful!")
    
   // Accessing subclass method
   result1.display() 
} else {
   print("Downcast is unsuccessful")
}

// Here the conditional downcasting will be unsuccessful
let newObj: ProgrammingLanguage = ProgrammingLanguage()

if let result2 = newObj as? Swift {
   print("\nDowncast is successful!")
   result2.display()
} else {
   print("Downcast is unsuccessful")
}
輸出

它將產生以下輸出:

Downcast is successful!
Welcome to Swift tutorial
Downcast is unsuccessful

強制向下轉型 (as!)

強制向下轉型 (as!) 運算子用於強制將例項向下轉換為給定的子類型別。此運算子將返回子類例項。如果向下轉型不成功,則會引發執行時錯誤。此運算子通常在我們確定向下轉型一定會成功時使用。

語法

以下是強制向下轉型 (as!) 的語法:

let constantName = instance as! type

示例

Swift 程式,演示如何使用強制向下轉型運算子 (as!)。

// Base Class
class ProgrammingLanguage {
   func show() {
      print("Welcome to the great world of learning")
   }
}

// Subclass
class Swift: ProgrammingLanguage {
   func display() {
      print("Welcome to Swift tutorial")
   }
}
let obj: ProgrammingLanguage = Swift()

// Here the forced downcasting will be successful
let res1 = obj as! Swift

// Accessing the method of Swift class
res1.display()

// Here the forced downcasting will be successful so we will get an error
/*let newobj: ProgrammingLanguage = ProgrammingLanguage()
let res2 = newobj as! Swift
res2.display()*/
輸出

它將產生以下輸出:

Welcome to Swift tutorial

型別檢查

在 Swift 中,型別檢查用於確定給定例項是否屬於指定的子類。我們可以使用 is 運算子執行型別檢查。如果例項屬於指定的類,則此運算子將返回 true。如果例項不屬於指定的類,則此運算子將返回 false。

語法

以下是型別檢查的語法:

let constantName = instance as! type

示例

Swift 程式,演示如何檢查例項的型別。

// Base Class
class ProgrammingLanguage {
   func show() {
      print("Welcome to the great world of learning")
   }
}

// Subclass
class Swift: ProgrammingLanguage {
   func display() {
      print("Welcome to Swift tutorial")
   }
}

let obj: ProgrammingLanguage = Swift()

// Type Checking
if obj is Swift{
   print("obj is the instance of Swift class")
} else {
   print("No obj is not the instance of Swift class")
}

輸出

它將產生以下輸出:

obj is the instance of Swift class

Any 和 AnyObject 的型別轉換

Swift 支援兩種用於處理未知型別的值和類例項的特殊型別,它們是

  • Any - Any 用於表示屬於任何型別的例項,包括函式型別。它還包括可選型別。

  • AnyObject - AnyObject 用於表示任何類型別的例項。

我們可以對 Any 和 AnyObject 執行型別轉換和型別檢查。

示例

Swift 程式,演示 Any 的型別轉換。

// Type Casting for Any
var myValue: Any = 22

// Type Checking using is operator 
if myValue is Int {
   print("Yes myValue is of Int type!")
} else {
   print("No myValue is not of Int type!")
}

// Type Casting using as? operator
if let res = myValue as? Int {
   print("Successfully casted to Int: \(res)")
} else {
   print("Could not be able to cast into Int")
}

輸出

它將產生以下輸出:

Yes myValue is of Int type!
Successfully casted to Int: 22

示例

Swift 程式,演示 AnyObject 的型別轉換。

// Base Class
class ProgrammingLanguage {
   func show() {
      print("Welcome to the great world of learning")
   }
}

// Subclass
class Swift: ProgrammingLanguage {
   func display() {
      print("Welcome to Swift tutorial")
   }
}

// Instance of any object type
let obj: AnyObject = Swift()

// Type Checking using is operator
if obj is Swift {
   print("Yes it is the instance of Swift")
} else {
   print("No it is not the instance of Swift")
}

// Type Casting using as? operator
if let res = obj as? Swift {
   print("Successfully casted to Swift")
   res.display()
} else {
   print("Could not cast to Swift")
}

輸出

它將產生以下輸出:

Yes it is the instance of Swift
Successfully casted to Swift
Welcome to Swift tutorial
廣告