Is it possible to have a generic protocol in swift? I tried protocol foo<T>{}
and that is not legal. I'm looking for something that can be used similarly to Java's List<T>
interface.
Generics in Swift allows you to write generic and reusable code, avoiding duplication. A generic type or function creates constraints for the current scope, requiring input values to conform to these requirements.
Generic Protocols are for procedures/techniques involving human participants that are used on a regular basis, and which form all or part of subsequent research projects or taught modules.
In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes (or any other types). We use the protocol keyword to define a protocol. For example, protocol Greet { // blueprint of a property var name: String { get } // blueprint of a method func message() }
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".
There is no such thing as generics for protocols. But there is something else, which ressembles a lot to the generics when you look at it.
Here is an example taken from the Swift standard library:
protocol Generator {
typealias Element
func next() -> Element?
}
The Swift book scratches the surface in the Generics chapter, Associated Types.
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