我应该快速使用static vs枚举

时间:2019-02-09 09:25:32

标签: swift struct enums static

iOS 12,Swift 4.2

这两个都做同一件事,哪个更好?

private struct fieldV {
  static let billV = 1
  static let centV = 2
  static let payerV = 3
}

private enum fieldInt: Int {
  case bill
  case cent
  case payers
}

使用第一个更为明显,所以我明白了。

percent.tag = fieldV.centV 

对比

percent.tag = fieldInt.cent.rawValue

确定我要说的是3个不同的Int和一个可以具有三个值之一的Int吗?但是,有更好的理由使用其中一个吗?

2 个答案:

答案 0 :(得分:1)

Struct and enums are fundamentally different in the sense that :

  1. Structs like classes are product types. This means to represent an object of a struct you need all the fields. For example lets take a struct Employee with two fields name and address. An employee in this case is defined by both address and name.
  2. On the other hand enums are sum type. This means they are represented by any of the field. For example let's take an enum NetworkStatus which can be either SUCCESS or FAILURE

Notice that in struct (and also classes, tuples) information representation happens by all of their fields while in case of enums information representation happens by any of their fields.

In your case clearly structs is the correct answer as you need bill, cent and payers all three of the fields to represent the complete information.

答案 1 :(得分:1)

当您限制已知选项时,应使用枚举枚举可以为CaseIterable,您可以一次使用all的情况!您可以在枚举上switch,如果不使用default大小写,它将自动跟踪案例的添加和删除。这些对于struct或类是不可能的。即使您想直接使用Int而不使用rawValue的值,也应考虑在枚举内部使用 static

private enum Field {
  static let bill = 1
  static let cent = 2
  static let payer = 3
}

正如您的案例命名一样,看起来Int值是您要比较的东西,或者应该发送给服务器等的东西,它不是Field本身的一部分。因此,我建议您使用除rawValue之外的一些计算属性!

private enum Field {
    case bill
    case cent
    case payers

    var intValue: Int {
        switch self {
        case .bill: return 1
        case .cent: return 2
        case .payers: return 3
        }
    }
}

这可能会导致您花费更多时间和精力,但更加方便且防错。您可以根据需要添加自定义初始化程序。

-还有一件事情

请迅速考虑将大驼峰大写字母名称用于类型。 (枚举,结构,类)