11

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.

pseudonym117
  • 799
  • 1
  • 5
  • 22
  • `List` is `Array` in Swift... No need for protocols there. – Sulthan Aug 01 '14 at 14:47
  • Well I don't want a list specifically, I want to make a custom provider interface. List was just the interface in java that I knew wasn't implemented in swift (as a protocol) and was a generic interface – pseudonym117 Aug 01 '14 at 15:03
  • Oh, I forgot that `List` in Java is an interface and not an abstract class. I understand your question now. – Sulthan Aug 01 '14 at 15:05

2 Answers2

11

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.

0

It's possible to achieve the same functionality of a Java List Interface in Swift using a protocol with an associated type declaration.

//  Created by Juan Miguel Pallares Numa on 2/24/20.
//  Copyright © 2020 Juan Miguel Pallares Numa. All rights reserved.

import Foundation

protocol List {

    // An associated type gives a placeholder name to a type
    // that is used as part of the protocol.
    associatedtype Element

    func add(index: Int, element: Element)
    func get(index: Int) -> Element
}

class ArrayList<Element>: List {

    private var items: [Element] = []

    func add(index: Int, element: Element) {
        items.insert(element, at: index)
    }

    func get(index: Int) -> Element {
        return items[index]
    }
}

let arrayOfInts = ArrayList<Int>()
let arrayOfStrings = ArrayList<String>()

arrayOfInts.add(index: 0, element: 17)
arrayOfInts.add(index: 1, element: 19)
print("arrayOfInts[1] is \(arrayOfInts.get(index: 1))")
// arrayOfInts[1] is 19

arrayOfStrings.add(index: 0, element: "Generics - The Swift Programming Language")
print("arrayOfStrings[0] is \(arrayOfStrings.get(index: 0))")
// arrayOfStrings[0] is Generics - The Swift Programming Language

/* (lldb) expr print(arrayOfInts.items)
[17, 19]
(lldb) expr print(arrayOfStrings.items)
["Generics - The Swift Programming Language"] */

The documentation speaks best for itself. Please see Associated Types in https://docs.swift.org/swift-book/LanguageGuide/Generics.html#ID189

Juanmi
  • 71
  • 1
  • 1
  • 7