I have an interesting constraint/invariant and I would love to hear people's input on how to maintain it. Big bonus if it can be ensured at compile time...

I have the types below, and the following conceptual invariant... If an attribute's id equals an attributeValue's id, then they must have corresponding types. How would you express this invariant and ensure it is true in code? (The code is Swift, but the question is generic. For those that don't know Swift, these are all immutable value types. They can be used just like integers or immutable strings in other languages.)

struct Attribute {
    let attributeID: Int
    let name: String
    let display: Bool
    let type: AttributeType

enum AttributeType {
    case Text
    case SingleList([AttributeChoice])
    case MultiList([AttributeChoice])
    case Date
    case Time
    case DateTime
    case Image
    case Flag
    case Count

struct AttributeValue {
    let attributeID: Int
    let value: AttributeValueType

enum AttributeValueType {
    case Text(String)
    case SingleList(AttributeChoice)
    case MultiList([AttributeChoice])
    case Date(NSDate)
    case Time(NSDate)
    case DateTime(NSDate)
    case Image(UIImage)
    case Flag(Bool)
    case Count(Int)

struct AttributeChoice {
    let serverID: Int
    let name: String

As I am writing this question, I was thinking that maybe the Attribute class should manage the creation of AttributeValues somehow, any other ideas?

  • 1
    Is there any reason AttributeValue has an AttributeID rather than an Attribute other than "that's how the DB stores them"?
    – Telastyn
    Commented Jul 15, 2015 at 13:27
  • Yes, I communicate with the back-end by ID number, but I think that I should have some more obvious way of linking them than simply "same ID number" so if you have any ideas, I would love to hear them.
    – Daniel T.
    Commented Jul 15, 2015 at 13:31
  • Well, at least in some languages, you can make an Attribute<T> which then can be required to have the same T as AttributeValue<T>.
    – Telastyn
    Commented Jul 15, 2015 at 13:35
  • The problem is that Attribute and AttributeValue don't have identical types, they have corresponding types.
    – Daniel T.
    Commented Jul 15, 2015 at 13:38
  • Ah, I see. Interesting.
    – Telastyn
    Commented Jul 15, 2015 at 13:41


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.