Overview
Generics are extremely useful in any programming language. This post is all about generics in swift as the title implies. You can find more information about swift generics here.
Content
Class
1
2
3
4
5
6
7
8
9
struct Stack<T> {
    var items = [T]()
    mutating func push(item: T) {
        items.append(item)
    }
    mutating func pop() -> T {
        return items.removeLast()
    }
}
Methods/Functions
1
2
3
4
5
func swapTwoValues<T>(inout a: T, inout b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}
Type Constraints
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func allItemsMatch<C1: Container, C2: Container 
    where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
    (someContainer: C1, anotherContainer: C2) -> Bool {
        // check that both containers contain the same number of items
        if someContainer.count != anotherContainer.count {
            return false
        }
        
        // check each pair of items to see if they are equivalent
        for i in 0..<someContainer.count {
            if someContainer[i] != anotherContainer[i] {
                return false
            }
        }
        
        // all items match, so return true
        return true
}