Swift:如何将枚举值转换为字符串?

swiftserver side programmingprogramming更新于 2025/9/22 16:22:17

在 Swift 中,您可以通过 rawValue 属性将枚举值转换为字符串。前提是枚举的原始值类型为 String。如果枚举没有原始值,您可以使用 String(describing:) 初始化器获取枚举值的字符串表示形式。此外,您还可以使用 CustomStringConvertible 协议。

示例 1

使用 rawValue 属性将枚举值转换为字符串。在此示例中,Fruit 是一个原始值为 String 类型的枚举。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("枚举值:\(fruitString)")

输出

枚举值: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("枚举值:\(directionString)")

输出

枚举值: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 中,有几种方法可以将枚举值转换为字符串 -

  • 如果枚举值的原始值为 String 类型,则可以使用 rawValue 属性检索其字符串表示形式。

  • 您可以实现 CustomStringConvertible 协议,并提供您自己的 description 属性或方法实现。如果您希望自定义枚举项的字符串表示形式,则可以这样做。

  • 如果枚举值缺少原始值,并且您不想提供特定的字符串表示形式,请使用 String(describing:) 初始化器获取枚举值的默认字符串表示形式。

根据您的具体用例需求,选择最符合您需求的策略。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部