Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Generic Protocol

Tags:

swift

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.

like image 528
pseudonym117 Avatar asked Aug 01 '14 14:08

pseudonym117


People also ask

What is a generic Swift?

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.

What is a generic protocol?

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.

What is a Swift protocol?

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() }

How do I create a generic protocol?

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".


1 Answers

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.

like image 100
fabrice truillot de chambrier Avatar answered Nov 15 '22 23:11

fabrice truillot de chambrier