1. 程式人生 > >Swift:泛型專題

Swift:泛型專題

1. 泛型函式

import Foundation

func swapTwoThings<T> (a: inout T, b: inout T) {
    (a, b) = (b, a)
}

var a = 1
var b = 2
swapTwoThings(a: &a, b: &b)
a
b

var aa = "I love you"
var bb = "you love him"
swapTwoThings(a: &aa, b: &bb)
aa
bb

2. 泛型型別初體驗

import Foundation

struct Stack<T> {
    var items = [T]()
    func isEmpty() -> Bool {
        return items.isEmpty
    }
    
    mutating func push(item: T) {
        items.append(item)
    }
    
    mutating func pop() -> T? {
        guard !isEmpty() else {
            return nil
        }
        return items.removeLast()
    }
}

extension Stack {
    var top: T? {
       return items.last
    }
}

var s = Stack<Int>()
s.isEmpty()
s.pop()
s.push(item: 2)
s.top
s.pop()
s.top

3. 尖括號裡可以有多種型別

import Foundation

struct Pair<T1, T2> {
    var a: T1
    var b: T2
}

var pair = Pair<Int, String>(a: 2, b: "hahaha")
pair.a
pair.b