Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can this protocol "only be used as a generic constraint"?

I'm attempting to do the following in Swift:

protocol ProtocolWithAlias {     typealias T }  protocol AnotherProtocol {     func someFunc() -> ProtocolWithAlias } 

But I get the error: Protocol 'ProtocolWithAlias' can only be used as a generic constraint because it has Self or associated type requirements.

Is it possible to do something like this? The error message (or at least the "only be used as a generic constraint" part) doesn't seem to make much sense to me.

I'm using the latest Xcode 6 beta 3.

Thanks!

like image 356
MatthewSot Avatar asked Jul 12 '14 01:07

MatthewSot


People also ask

What can protocols use to make them generic like?

Making a Protocol Generic. There are two ways to create a generic protocol - either by defining an abstract associatedtype or the use of Self (with a capital S). The use of Self or associatedtype is what we like to call "associated types". This is because they are only associated with the protocol they are defined in.

What is Associatedtype Swift?

What is an associated type? An associated type can be seen as a replacement of a specific type within a protocol definition. In other words: it's a placeholder name of a type to use until the protocol is adopted and the exact type is specified.

What is type erasure Swift?

Type-erasure simply means "erasing" a specific type to a more abstract type in order to do something with the abstract type (like having an array of that abstract type). And this happens in Swift all the time, pretty much whenever you see the word "Any."

What is some in Swift?

The some keyword was introduced in Swift 5.1 and is used to define an Opaque Type. An opaque type is a way to return a type without needing to provide details on the concrete type itself. It limits what callers need to know about the returned type, only exposing information about its protocol compliance.


1 Answers

Try this:

func someFunc<T:ProtocolWithAlias>() -> T 
like image 175
Catfish_Man Avatar answered Sep 20 '22 18:09

Catfish_Man