Skip to content

Instantly share code, notes, and snippets.

@richimf
Last active September 29, 2019 21:26
Show Gist options
  • Save richimf/f8ddb5efe5b3932b9d9cb886b606b6d2 to your computer and use it in GitHub Desktop.
Save richimf/f8ddb5efe5b3932b9d9cb886b606b6d2 to your computer and use it in GitHub Desktop.
Protocol with Generics
import UIKit
// Creamos un Protocolo
protocol Beverage {
func brewed() -> Self
}
//Creamos una funcion Generic donde el tipo T conforma al Protocolo
func serve<T>(_ drink: T) -> T where T: Beverage {
print("Se ejecuto metodo del generic \(drink.self)")
return drink.brewed()
}
// Creamos una Struct que conforme el Protocolo
struct Coffee: Beverage {
// Esto crea un setter private y un getter del nivel de acceso de la estructura.
private(set) var isBrewed = false
//Protocol methods
func brewed() -> Coffee {
return Coffee(isBrewed: true)
}
}
let coffee = Coffee()
//La funcion "serve" acepta a "coffee" porque ambos conforman el mismo protocolo.
let servedCoffee = serve(coffee) // "serve" ejecutara la funcion "brewed()" de "coffee".
print(servedCoffee)
/// OTRO EJEMPLO
// Un Generic en un protocol utilia la palabra "associatedtype".
protocol Stackable: class { // "class" indica que solo clases puede conformar este protocolo.
associatedtype Element // <- una variable, cualquiera.
func push(_ element: Element)
func pop() -> Element?
}
class Stack<Element>: Stackable {
var storage: [Element] = []
// Funciones del Protocol:
func push(_ element: Element) {
storage.append(element)
}
func pop() -> Element? {
return storage.popLast()
}
}
// Creamos dos instancias de Stack.
var stack1: Stack<Int> = Stack<Int>()
var stack2: Stack<Int> = Stack<Int>()
// Definimos una funcion que utilizará el protocolo "Stackable"
func pushToAll<S: Stackable>(stacks: [S], value: S.Element) {
stacks.forEach {
$0.push(value)
}
}
// Como cada stack es de tipo Stack<T> que conforma el protocolo "Stackable", podemos pasarlos como parametros.
pushToAll(stacks: [stack1, stack2], value: 9)
print(stack1.storage) // [9]
print(stack2.storage) // [9]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment