Swift Basics - Generics


We use generics when we need to create functions that can be used with multiple types.

If I wish to create a function that swaps 2 objects, I will need to create a function for each type, without generics:
func swapInt(a: Int, b: Int){}
func swapString(a: String, b: String){}
func swapDouble(a: Double, b: Double){}

We can condense all 3 into one function that makes use of a generic type:
func swap<T>(a: T, b: T){}

T is the generic type assigned.

You can also choose another name for T:
func swap<XYZ>(a: XYZ, b: XYZ)

If there are multiple types, we can use different name placeholders for the types:
func swap<T, E>(a: T, b: E){}

To call the function:
var a = 5
var b = 10
swap(a: &a, b: &b)

//placing & before a and b just ensures that their values get updated and persists outside of the function

A generic type is a class, structure or enumeration that can work with any type.
We can create a class of a generic type:
class Listing<G>{
 var items = [G]()

 func add(item: G)
 {
 items.append(item)
 }
}

To instantiate it:
var a = Listing<String>()
var b = Listing<Int>()
var c = Listing<Double>()

If we want to ensure that the type listed is comparable (confirms to comparable protocol - types like String, Int, Double), when creating the class:

class Listing<G, Comparable>()

You can also create generic subscripts:
subscript<T: Hashable>(item: T) -> Int {return item.hashValue}
//Hashable means that it conforms to the hashable protocol.

Generics can also be used as a return type:

subscript<T>(key: String) -> T?{ return dictionary[key] as? T}

Associated types:

Associated types are like generic types used inside protocols:

protocol Proto1
{
 associatedtype T
 mutating func add(item: T)
 mutating func getItem() -> T?
}

To use it:
class IntProto: Proto1
{
  var item = 3
  func add(item: Int)
{}
 func getItem() -> Int?
{ return self.item}
}

We can also create a class that implements the protocol with a generic type:

class ClassA<G>: Proto1
{
  var item: G
  func add(item: G) {}
  func getItem()->G?{}

}

When defining the associated type, we can ensure that it is hashable:
associatedType T: Hashable


Comments

Popular posts from this blog

Setting up a playground

Go to another page