lunes, 13 de octubre de 2014

Swift y Tipos Genéricos (Generics)


Generic es una característica de Swift que te permite reutilizar funciones.
Un tipo Array y Dictionary son colecciones de genéricos. 
Puedes crear una Array que contenga tipos Int, String u otro tipo, igual pasa con los Dictionary.
En el caso de tener una struct que contenga un Array de tipo String, con un método poner y quitar.

struct ContenidoString{
   var valores: String [];
       mutating func poner(x: String){
            valores += x
        }

      mutating func quitar() -> String {
          return valores.removelast()
      }
}

Para que esta struct sea genérica
struct Contenido <T> {
 var valores: T [];
       mutating func poner(x: T){
            valores += x
        }

      mutating func quitar() -> T {
          return valores.removelast()
      }
}

Utilización :
var contenidoEnteros = Contenido<Int>()
contenidoEnteros.poner(100)
var contenidoEnteros = Contenido<String>()
contenidoEnteros.poner(@"100")








No hay comentarios:

Publicar un comentario