Today someone commented on this code and suggested it would be better in an enum:
typealias PolicyType = (filename: String, text: String)
struct Policy {
static let first = PolicyType(filename: "firstFile.txt", text: "text in first file")
static let second = PolicyType(filename: "secondFile.txt", text: "text in second file")
static let third = PolicyType(filename: "thirdFile.txt", text: "text in third file")
}
let thirdPolicyText = Policy.third.text
Is there a more memory efficient, maintainable way to do this with an enum? My primary objective is maintainability.
Below is what I've come up with:
enum Policy: RawRepresentable {
case one
case two
case three
var rawValue: (filename: String, text: String) {
switch self {
case .one:
return ("1", "policy 1 text")
case .two:
return ("2", "policy 2 text")
case .three:
return ("3", "policy 3 text")
}
}
init?(rawValue: (filename: String, text: String)) {
switch rawValue {
case ("1", "policy 1 text"):
self = .one
case ("2", "policy 2 text"):
self = .two
case ("3", "policy 3 text"):
self = .three
default:
return nil
}
}
}
At this point, I've figured out how to achieve similar functionality with a struct and an enum. The enum seems like a lot more maintenance if someone goes back to update it and it's more error prone. Paul Hegarty says line that won't crash is the line you don't write and the enum route looks and feels cumbersome.
Is there a memory advantage to going the enum route versus a struct?
When I'm done, I'd like to be able to pass around a Policy as a parameter, like so:
func test(for policy: Policy) {
print(policy.rawValue.filename)
print(policy.rawValue.text)
}
test(for: Policy.first)