Swift:如何將列舉值轉換為字串?
在 Swift 中,您可以透過 `rawValue` 屬性將列舉值轉換為字串。前提是該列舉具有字串型別的原始值。如果列舉沒有原始值,則可以使用 `String(describing:)` 初始化器來獲取列舉值的字串表示形式。此外,您還可以使用 `CustomStringConvertible` 協議。
示例 1
使用 `rawValue` 屬性將列舉值轉換為字串。在本例中,`Fruit` 是一個具有字串型別原始值的列舉。`rawValue` 屬性用於獲取 `myFruit` 列舉值的字串表示形式,即“Apple”。
import Foundation
enum Fruit: String {
case apple = "Apple"
case banana = "Banana"
case orange = "Orange"
}
let myFruit = Fruit.apple
let fruitString = myFruit.rawValue
print("Enum value: \(fruitString)")
輸出
Enum value: Apple
示例 2
如果列舉沒有原始值,則可以使用 `String(describing:)` 初始化器來獲取列舉值的字串表示形式。在本例中,`Direction` 是一個沒有原始值的列舉。`String(describing:)` 初始化器用於獲取 `myDirection` 列舉值的字串表示形式,即“north”。
import Foundation
enum Direction {
case north
case south
case east
case west
}
let myDirection = Direction.north
let directionString = String(describing: myDirection)
print("Enum value: \(directionString)")
輸出
Enum value: north
示例 3
自定義列舉的字串表示形式。在本例中,我們有一個名為 `Suit` 的列舉,它實現了 `CustomStringConvertible` 協議。我們提供了 `description` 屬性的自定義實現,該屬性返回每種花色的相應符號。當我們建立一個 `Suit` 例項並列印它時,將使用自定義字串表示形式。
import Foundation
enum Suit: CustomStringConvertible {
case spades, hearts, diamonds, clubs
var description: String {
switch self {
case .spades:
return "♠︎"
case .hearts:
return "♥︎"
case .diamonds:
return "♦︎"
case .clubs:
return "♣︎"
}
}
}
let suit = Suit.hearts
print(suit)
輸出
♥︎
結論
總之,在 Swift 中有多種方法可以將列舉值轉換為字串:
如果列舉具有字串型別的原始值,則可以使用 `rawValue` 屬性來檢索列舉值的字串表示形式。
您可以實現 `CustomStringConvertible` 協議並提供您自己的 `description` 屬性或方法的實現。如果您希望自定義列舉項的字串表示形式,則可以使用此方法。
如果列舉沒有原始值並且您不想提供特定的字串表示形式,則可以使用 `String(describing:)` 初始化器來獲取列舉值的預設字串表示形式。
根據您特定用例的需求,選擇最符合您需求的策略。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP