ra1028 / DifferenceKit

💻 A fast and flexible O(n) difference algorithm framework for Swift collection.

Home Page:https://ra1028.github.io/DifferenceKit

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

how can we declare an array with protocol that extends from Differentiable

ruixingchen opened this issue · comments

my datasource is an array with a protocol like

protocol Entity {
    var title:String {get}
    var id:String {get}
    and so ......
}

var dataSource:[Entity] = []

the code works good
but if I extends the protocol with Differentiable :

protocol Entity:  Differentiable {
    var title:String {get}
    var id:String {get}
}

var dataSource:[Entity] = []

xcode says that Protocol 'Entity' can only be used as a generic constraint because it has Self or associated type requirements

now my solution is copying your codes in to my project and delete the DifferenceIdentifier in Differentiable and change func isContentEqual(to source: Self) -> Bool to func isContentEqual(to source: Any) -> Bool

but is there any better solutions ?
thanks, DifferenceKit is awesome

@ruixingchen
Swift Array is not allowed to use existential type that have associated type to Element.
You can extends the Differentiable protocol by wrapping it with struct or enum.
e,g.

struct EntityWrapper: Differentiable {
    var base: Entity
    var id: String    { base.id }

    ...
}

var dataSource: [EntityWrapper] = []
struct A: Entity {...}
struct B: Entity {...}
struct C: Entity {...}

enum EntityVariant: Differentiable {
    case a(A)
    case b(B)
    case c(C)

   ...
}

var dataSource: [EntityVariant] = []

@ra1028
thanks, but sadly not working 😢

struct EntityWrapper: Differentiable {
    var base: Entity //ERROR HERE
    var id: String    { base.id }
    ...
}

Xcode says that Protocol 'Entity' can only be used as a generic constraint because it has Self or associated type requirements

I used associatedType in one of my protocol, but then the protocol comes to be nothing, it can only be used as a generic constraint, I cant use it as a TYPE, or put it in an array, at last I remove the associatedType and use Any instead, now the protocol is free and wild 😜

@ruixingchen
I looked at your sample code and suggested to implement it with wrapper type because Entity can be used as an existential type if the Differentiable conformance is removed from it.
If the Entity has an associated type for other reasons, I recommend to use the enum that I suggested before.
The further discussion will be about Swift's existential type, and the issue will deviate from "how to use DifferenceKit".