Reputation: 8995
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
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.
In swift, you should consider using upper camel case names for types. (Enum, Struct, Class)
Upvotes: 1
Reputation: 2207
Struct and enums are fundamentally different in the sense that :
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