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!
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 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.
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."
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.
Try this:
func someFunc<T:ProtocolWithAlias>() -> T
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With