0

Suppose you want to keep track of one or more unique identifier(s). In this case, A has two properties that are considered unique to A, while B has only one property that is unique to B.

protocol HavingUID {
   // Some way to use KeyPath?
}

struct A : HavingUID {
   var unique1 : String  
   var unique2 : Int
}

struct B : HavingUID {
   var unique1 : Double
}

let a1 = A(unique1:"val", unique2: 1)
let a2 = A(unique1:"val", unique2: 2)
let b1 = B(unique1:0.5)
let b2 = B(unique1:0.0)
let b3 = B(unique1:0.2)

let arrA : [HavingUID] = [a1,a2]
let arrB : [HavingUID] = [b1,b2,b3]

// How to check arrA and arrB for duplicate UID properties?

If there was just one unique key, we could do something like:

protocol HavingUID {
   typealias UID
   static var uidKey : KeyPath<Self, UID> {get}
}
struct A : HavingUID {
   static var uidKey = A.\unique1
   var unique1 : String
}
struct B : HavingUID {
   static var uidKey = B.\uniqueB
   var uniqueB : Int
}

...but that limits me to one key.

GoldenJoe
  • 7,874
  • 7
  • 53
  • 92
  • When you say "A has two unique properties", does that mean if any of the two properties are different, then the two `A`s are considered different? Or does that mean two `A`s are considered different if and only if both properties are different? – Sweeper Sep 04 '20 at 02:33
  • And I don't really understand why you are using key paths. Can't you just do something like what [`Identifiable`](https://developer.apple.com/documentation/swift/identifiable) does? – Sweeper Sep 04 '20 at 02:37
  • @sweeper That doesn't matter for the purpose of the question, but for sake of the example let's keep it simple and just say that a property will only ever be compared to the same property in a different instance. The reason `Identifiable` is insufficient is because it is limited to one `id` property. I'm considering a case where there are multiple unique properties, that may not even be named "id". – GoldenJoe Sep 04 '20 at 02:46

1 Answers1

0

Any time you need to use unique identifiers, you definitely should keep track of them with global structs or enums. Here are two easy ways to do this:

Structs:

struct UniqueIdentifiers {
    static let id1 = "identifier_one"
    static let id2 = "identifier_two"
    static let id3 = "identifier_three"
}

let currentID = UniqueIdentifiers.id1

Enums:

enum UniqueIdentifiers: String {
    case id1 = "identifier_one"
    case id2 = "identifier_two"
    case id3 = "identifier_three"
}

let currentID = UniqueIdentifiers.id1.rawValue
nicksarno
  • 3,850
  • 1
  • 13
  • 33