Andrey Zakharchenko
Andrey Zakharchenko

Reputation: 23

Swift generics complex inheritance

The following Swift code does not compile:

class Entity {

}

class EntityConverter<T: Entity> {

}

class GetEntityServerAction<T: Entity, C: EntityConverter<T>> {

}

class GetEntityListServerAction<T: Entity, C: EntityConverter<T>>: GetEntityServerAction<T, C> {

}

with the error:

Type 'C' does not inherit from 'EntityConverter<T>'

for the GetEntityListServerAction class definition. For some reasons the compiler doesn't see that C parameter is defined like inheriting exactly the same type it wants.

The code should look rather simple for those who are used to complicated generic hierarchies in Java or C# but the Swift compiler doesn't like something indeed.

Upvotes: 2

Views: 207

Answers (1)

Airspeed Velocity
Airspeed Velocity

Reputation: 40955

You might find that using protocols and associated types is the more Swift-like way of doing things:

class Entity { }

protocol EntityConversionType {
    // guessing when you say conversion, you mean from something?
    typealias FromEntity: Entity
}

class EntityConverter<FromType: Entity>: EntityConversionType {
    typealias FromEntity = FromType
}

class GetEntityServerAction<T: Entity, C: EntityConversionType where C.FromEntity == T> {  }

class GetEntityListServerAction<T: Entity, C: EntityConversionType where C.FromEntity == T>: GetEntityServerAction<T, C> { }

let x = GetEntityListServerAction<Entity, EntityConverter<Entity>>()

Possibly GetEntityServerAction can also be represented by just a protocol, and that you could convert Entity, EntityConverter and GetEntityListServerAction to structs, also.

Upvotes: 1

Related Questions