返回

Swift10 - 枚举(enum)探索(续)

IOS

探索枚举的各种形式

结构体枚举(Struct Enum)

enum Suit: String {
    case hearts = "♥"
    case diamonds = "♦"
    case clubs = "♣"
    case spades = "♠"
}

以上枚举被称为结构体枚举,因为它使用了原始值(Raw Value),原始值类型为字符串。SIL 文件如下:

// 枚举定义
enum Suit : String {
  case hearts = "♥"
  case diamonds = "♦"
  case clubs = "♣"
  case spades = "♠"
}

元组枚举(Tuple Enum)

enum Suit: (String, String) {
    case hearts = ("Heart", "♥")
    case diamonds = ("Diamond", "♦")
    case clubs = ("Club", "♣")
    case spades = ("Spade", "♠")
}

此枚举称为元组枚举,它使用元组作为关联值。SIL 文件如下:

// 枚举定义
enum Suit : (String, String) {
  case hearts = ("Heart", "♥")
  case diamonds = ("Diamond", "♦")
  case clubs = ("Club", "♣")
  case spades = ("Spade", "♠")
}

关联值枚举(Associated Value Enum)

enum Card {
    case number(Int)
    case face(String)
}

此枚举称为关联值枚举,它使用关联值来提供更多信息。SIL 文件如下:

// 枚举定义
enum Card {
  case number(Int)
  case face(String)
}

泛型枚举(Generic Enum)

enum Box<T> {
    case empty
    case full(T)
}

此枚举称为泛型枚举,它可以存储任何类型的值。SIL 文件如下:

// 枚举定义
enum Box<T> {
  case empty
  case full(T)
}

总结

本篇文章深入探索了Swift枚举类型的内部结构和实现细节,包括结构体枚举、元组枚举、关联值枚举和泛型枚举。通过分析SIL文件,我们了解了枚举的内存布局、调用流程以及它们是如何工作的。