Swift Generics Protocols: Can Only Be Used as a Generic Constraint Problem

Protocol can only be used as a generic constraint because it has Self or associatedType requirements

Suppose for the moment we adjust your protocol to add a routine that uses the associated type:

public protocol RequestType: class {
associatedtype Model
var path: String { get set }

func frobulateModel(aModel: Model)
}

And Swift were to let you create an array of RequestType the way you want to. I could pass an array of those request types into a function:

func handleQueueOfRequests(queue: [RequestType]) {
// frobulate All The Things!

for request in queue {
request.frobulateModel(/* What do I put here? */)
}
}

I get down to the point that I want to frobulate all the things, but I need to know what type of argument to pass into the call. Some of my RequestType entities could take a LegoModel, some could take a PlasticModel, and others could take a PeanutButterAndPeepsModel. Swift is not happy with the ambiguity so it will not let you declare a variable of a protocol that has an associated type.

At the same time it makes perfect sense to, for example, create an array of RequestType when we KNOW that all of them use the LegoModel. This seems reasonable, and it is, but you need some way to express that.

One way to do that is to create a class (or struct, or enum) that associates a real type with the abstract Model type name:

class LegoRequestType: RequestType {
typealias Model = LegoModel

// Implement protocol requirements here
}

Now it's entirely reasonable to declare an array of LegoRequestType because if we wanted to frobulate all of them we know we would have to pass in a LegoModel each time.

This nuance with Associated Types makes any protocol that uses them special. The Swift Standard Library has Protocols like this most notably Collection or Sequence.

To allow you to create an array of things that implement the Collection protocol or a set of things that implement the sequence protocol, the Standard Library employs a technique called "type-erasure" to create the struct types AnyCollection<T> or AnySequence<T>. The type-erasure technique is rather complex to explain in a Stack Overflow answer, but if you search the web there are lots of articles about it.

Swift 5.7 Existentials

Swift 5.7 introduces explicit existential using the any keyword. This will remove the "Protocol can only be used as a generic constraint…" error, but it doesn't solve the fundamental problem with this example. (Admittedly this example is academic, for demonstration purposes, and likely not useful in real code because of its limitations. But it also demonstrates how explicit existentials aren't a panacea.)

Here is the code sample using Swift 5.7 and the any keyword.

public protocol RequestType: AnyObject {
associatedtype Model
var path: String { get set }

func frobulateModel(aModel: Model)
}

func handleQueueOfRequests(queue: [any RequestType]) {
// frobulate All The Things!

for request in queue {
request.frobulateModel(/* What do I put here? */)
}
}

Now our queue contains a collection of existentials and we no longer have the error about the "type cannot be used here because of Self or AssociatedType constraints". But it doesn't fix the underlying problem in this example because the frobulateModel method can still take an arbitrary type (the associated type of the entity conforming to the RequestType protocol).

Swift provides other mechanisms that can help compensate for this. In general you'd want constrain the Model value to expose behavior shared by all Models. The frobulateModel method might be made generic and have constraints on the parameter to follow that protocol. Or you could use Swift 5.7's primary associated types (SE-0346) to help constrain the behavior of Models at the protocol level.

So yes, explicit existentials can remove the error message that the OP asked about - but they are not a solution for every situation.

Also, keep in mind that existentials lead to indirection and that can introduce performance problems. In their WWDC session, Apple cautioned us to use them judiciously.

Protocol 'Line' can only be used as a generic constraint because it has Self or associated type requirements

When you added Hashable, that added Equatable, and that made this a Protocol with Associated Type (PAT) because Equatable is a PAT. A PAT is not a type; it's a tool for adding methods to other types.

You can't use a PAT as the type of a variable, you can't put it into an array, you can't pass it as a parameter directly, you can't return it as a value. The only point of a PAT is as a generic constraint (where L: Line). A PAT says what another concrete type must provide in order to be useable in some context.

How you should address this isn't clear. This doesn't really look like it should be a protocol at all. It depends on what code-reuse problem you're trying to solve here.

Protocols are generally about what something can do. Line seems like it's just trying to hide the implementation, without expressing anything; that's not a protocol. As written, there's no reason for generics or protocols here at all. What do the other implementations of Line look like? (I'm having trouble imagining how else you would possibly implement this type.)

I suspect the correct answer is to replace all of this with a Station struct and a Line struct. I'm not seeing where a protocol is pulling any weight.

Here's a way that I might implement what you're building, along with some new protocols to see what they're for. Some of this might be more than you'd need for this problem, but I wanted to show protocols in action.

// A protocol for "ID" types that automatically gives them handy inits
// Nested ID types mean that Line.ID can't get confused with Station.ID.
// The point of a protocol is to add additional features to a type like this.
protocol IDType: Hashable, ExpressibleByStringLiteral, CustomStringConvertible {
var value: String { get }
init(value: String)
}

extension IDType {
// For convenience
init(_ value: String) { self.init(value: value) }
// Default impl for ExpressibleByStringLiteral
init(stringLiteral value: String) { self.init(value: value) }
// Default impl for CustomStringConvertible
var description: String { return value }
}

struct Line: Equatable {
struct ID: IDType { let value: String }
let id: ID
let stations: [Station]
var origin: Station { return stations.first! } // We ensure during init that stations is non-empty
var terminus: Station { return stations.last! }

init(id: ID, origin: Station, stops: [Station], terminus: Station) {
self.id = id
self.stations = [origin] + stops + [terminus]
}
}

// Conforming Line to this protocol lets it print more beautifully.
extension Line: CustomStringConvertible {
var description: String { return "\(id): \(origin) -> \(terminus)" }
}

// Stations can't contain Line directly. These are value types, and that would be
// recursive. But this is nice because it lets us construct immutable Stations
// and then glue them together with Lines which may even be in independent
// systems (for example, the bus system might be separate from the rail system,
// but share stations)
struct Station: Hashable {
struct ID: IDType { let value: String }
let id: ID
let name: String

func lines(in system: System) -> [Line] {
return system.linesVisiting(station: self)
}
}

extension Station: CustomStringConvertible {
var description: String { return name }
}

struct System: Equatable {
let lines: [Line]

// Using Set here makes it clear there are no duplicates, and saves
// some hassle turning it back into an Array, but we could also just
// return Array here as Array(Set(...))
var stations: Set<Station> {
// Uniquify the stations
return Set(lines.flatMap { $0.stations })
}

func linesVisiting(station: Station) -> [Line] {
return lines.filter { $0.stations.contains(station) }
}
}

// Some examples of using it.
let stationNames = ["Shady Grove", "Bethesda", "Metro Center", "Glenmont",
"Wiehle-Reston East", "Largo Town Center"]

// Build up a few stations; obviously there are many more
let stations = Dictionary(uniqueKeysWithValues:
stationNames.map { ($0, Station(id: .init($0), name: $0)) })

// Define some lines
let redLine = Line(id: "OR",
origin: stations["Shady Grove"]!,
stops: [stations["Bethesda"]!, stations["Metro Center"]!],
terminus: stations["Glenmont"]!)

let silverLine = Line(id: "SV",
origin: stations["Wiehle-Reston East"]!,
stops: [stations["Metro Center"]!],
terminus: stations["Largo Town Center"]!)

// And glue them together into a system
let system = System(lines: [redLine, silverLine])

Protocol can an only be used as a generic constraint because it has Self or associated type requirements

A little late, but I think it's still a good exercise to come up with a clean solution for your problem.

Within the Filterable protocol, you can't use the protocol type QueryParameters as a return type because QueryParameters has an associatedtype. Also, it's not really what you want, because returning a protocol type doesn't mean it conforms to itself (ie. QueryParameters type doesn't conform to QueryParameters).

Instead, what you need to do is create an associatedtype that conforms to the protocol QueryParameters to be used as a return type:

protocol Filterable {
associatedtype T : QueryParameters
func parameters() -> T
}

Then you can make Transactions conform to Filterable using the same function you have in your question but returning the opaque type some QueryParameters rather than the protocol type QueryParameters. This way you can return any type that conforms to QueryParameters which is what you really wanted to do:

struct Transactions: Filterable {
func parameters() -> some QueryParameters {
let transactionFilters = TransactionFilters(isWithdrawal: true)
return TransactionParameters(page: 1, filters: transactionFilters)
}
}

I hope you find that helpful. BTW, I fixed the typo in TransactionParameters in my answer :)

Protocol can only be used as a generic constraint

Updated

Sorry, I make mistakes. But there is no way to cast a protocol with associated type.

Hope this will help.

As i known the routePresentable.getRouteLocations has nothing to do with protocol MapPresentable.

So you can divide RoutePresentable to two protocol:

protocol MapPresentable {
associatedtype AnnotationElement: MKAnnotation
var annotations: [AnnotationElement] { get }
}

class MapViewController<M: MapPresentable>: UIViewController {
var mapPresentable: M!

}

protocol RoutePresentable: MapPresentable, CanGetRouteLocations {}

protocol CanGetRouteLocations {
var getRouteLocations: [CLLocation] { get }
}

if let routePresentable = mapPresentable as? CanGetRouteLocations {
showRoute(routePresentable.getRouteLocations)
}

Original

Because routePresentable.annotations's Type is unprovided,

You can just remove associatedtype AnnotationElement: MKAnnotation.

Or user generic struct instead:

struct MapPresentable<AnnotationElement: MKAnnotation> {
var annotations: [AnnotationElement] = []
}

struct RoutePresentable<AnnotationElement: MKAnnotation> {
var mapPresentable: MapPresentable<AnnotationElement>
var getRouteLocations: [CLLocation] = []
}

class MapViewController<AnnotationElement: MKAnnotation>: UIViewController {

var mapPresentable: MapPresentable<AnnotationElement>!

}

if let routePresentable = mapPresentable as? RoutePresentable<MKAnnotation> {
showRoute(routePresentable.getRouteLocations)
}

Why do I get the error “Protocol … can only be used as a generic constraint because it has Self or associated type requirements”?

A function return type can only be a concrete Type.

The point is Type. Anything struct, class or Protocols that are completely defined in themselves are pure Type. However when a protocol or struct depend on another Generic Type Placeholder such as T, then this is a partial type.

Type are a data construct that compiler has to allocate certain memory.

So something like this:

let a = Array<T>() or let b = T is not sufficient information for the compiler to deduce at compile time.

Hence, this wont work.

  extension IntegerType {

func squared () -> IntegerType { // this line creates error

return self * self

}
}

Here, IntegerType is a partial type. It is a generic protocol that only when conformed can then we know the exact type. Similar to Array. Array itself is not a type. Its a generic container. Only when someone creates it with Array() or Array()... then it has a type.

The same happened with you.

public protocol IntegerType : _IntegerType, RandomAccessIndexType {

then again,

public protocol RandomAccessIndexType : BidirectionalIndexType, Strideable, _RandomAccessAmbiguity {
@warn_unused_result
public func advancedBy(n: Self.Distance) -> Self

then again,

   public protocol _RandomAccessAmbiguity {
associatedtype Distance : _SignedIntegerType = Int
}

Hence, as RandomAccessIndexType has Self requirement meaning until and unless someone conforms to it, Self is unknown placeholder. It is partial Type.

Since IntegerType conforms to the RandomAccessIndexType and _RandomAccessAmbuiguity which requires Distance associated type too.

Hence you cant do this too

let a: IntegerType = 12

Again IntegerType needs to know Self and Distance (associatedType).

Int however provides the details like so

public struct Int : SignedIntegerType, Comparable, Equatable {
/// A type that can represent the number of steps between pairs of
/// values.
public typealias Distance = Int

Hence you can do such

let a:Int = 10

because it provides Self for SignedIntegerType and Distance for its other counterpart.

Simply put it:

A partial type cannot be used where a concrete type can be. A partial type are good for other generics and constraining them.

What does Protocol ... can only be used as a generic constraint because it has Self or associated type requirements mean?

Protocol Observing inherits from protocol Hashable, which in turn inherits from protocol Equatable. Protocol Equatable has the following requirement:

func ==(lhs: Self, rhs: Self) -> Bool

And a protocol that contains Self somewhere inside it cannot be used anywhere except in a type constraint.

Here is a similar question.



Related Topics



Leave a reply



Submit