user3069232
user3069232

Reputation: 8995

static vs enum which should I use in swift

iOS 12, Swift 4.2

Both of these do the same thing, which is better?

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
}

To use the first is a little more obvious, so I got this.

percent.tag = fieldV.centV 

vs

percent.tag = fieldInt.cent.rawValue

Sure I am talking about 3 different Ints vs a single Int that can have one of three values? But is there a better reason to use one or the other?

Upvotes: 0

Views: 1950

Answers (2)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119868

When you have limited known options, you should use enum. Enum can be CaseIterable and you can use it cases all at once! You can switch on an enum and it automatically tracks adding and removing of cases if you don't use default case. These are not possible with struct or class. Even if you want to use Int value directly without rawValue you should consider using static inside enum like this:

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

As your case naming, It looks like Int value is something that you want to compare or something you should send to server or etc. and it's not part of the Field itself. So I recommend you to use some computed property except rawValue instead!

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
        }
    }
}

It may cause you more time and writing, but it's more convenient and bug-proof. You can add a custom initializer if you want.

- One More Thing

In swift, you should consider using upper camel case names for types. (Enum, Struct, Class)

Upvotes: 1

May Rest in Peace
May Rest in Peace

Reputation: 2207

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.

Upvotes: 1

Related Questions