I was in a code review today and someone said, "Why don't you do an enum on that?" I had started to, but conforming to a bunch of protocols seemed like a gigantic PITA and it seemed more error prone than just writing something simple, readable, and maintainable.
That said, I started to fiddle around with it this evening and I can't figure it out.
This is what I've started with:
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. It feels hacky and looks like...well, you know:
public struct PolicyType : Equatable, ExpressibleByStringLiteral {
var filename: String
var text: String
//MARK:- Equatable Methods
public static func == (lhs: PolicyType, rhs: PolicyType) -> Bool {
return (lhs.filename == rhs.filename && lhs.text == rhs.text)
}
//MARK:- ExpressibleByStringLiteral Methods
public init(stringLiteral value: String) {
let components = value.components(separatedBy: "|")
self.filename = components[0]
self.text = components[1]
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
}
enum Policy: PolicyType {
case first = "testFile1.txt|This is sample text"
case second = "testFile2.txt|This is more sample text"
case third = "testFile3.txt|This is more sample text"
}
Policy.third.rawValue.text
struct Policyandenum Policy: In the first case you have a type with 3 “predefined” values, but a program can create additional values, with arbitrary file names and texts. In the second case you have an enum with 3 values, and that's it. \$\endgroup\$