Creating an Enum with a Custom Type in Swift 4.x 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) -&gt; Bool {
    return (lhs.filename == rhs.filename &amp;&amp; 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
The code is using Enum, but it's still using Struct.
The program may be buggy if the text value has character |. Suppose that "testFile1.txt|This is sample text" to "testFile1.txt|This is | sample text".


I have another approach with Enum in this case:

 enum Policy {
    case first
    case second
    case third

    var fileName: String {
        switch self {
        case .first: return "testFile1.txt"
        case .second: return "testFile2.txt"
        case .third: return "testFile3.txt"
        }
    }

    var text: String {
        switch self {
            case .first : return "This is sample text"
            case .second: return "This is more sample text"
            case .third: return "This is more sample text"
        }
    }
}
   print(Policy.first.text)