Swift 范型 Generics

172 阅读1分钟
  • 定义一个交换Int类型的函数
    func swapTwoInts(a: inout Int,b:inout Int) {
        let temporaryA = a
        a = b
        b = temporaryA
    }
  • 定义一个交换String类型的函数
    func swapTwoStrings(a:inout String,b:inout String) {
        let temporaryA = a
        a = b
        b = temporaryA
    }
  • 定义一个交换Double类型的函数
    func swapTwoDoubles(a:inout Double,b:inout Double) {
        let temporaryA = a
        a = b
        b = temporaryA
    }
  • 实现
var someInt = 3
var anotherInt = 107
swapTwoInts(a: &someInt, b: &anotherInt)
print("someInt : \(someInt) , anotherInt : \(anotherInt)") // someInt : 107 , anotherInt : 3
  • 定义一个范型函数
    func swapTwoValues<T>(a:inout T,b:inout T) {
        let temporaryA = a
        a = b
        b = temporaryA
    }
var someInt = 3
var anotherInt = 107
swapTwoValues(a: &someInt, b: &anotherInt)
print("someInt : \(someInt) , anotherInt: \(anotherInt)") // someInt : 107 , anotherInt: 3
        
var someStr = "Hello"
var anotherStr = "World"
swapTwoValues(a: &someStr, b: &anotherStr)
print("someStr : \(someStr) , anotherStr: \(anotherStr)") // someStr : World , anotherStr: Hello
  • 定义一个Int栈结构体,如下
struct IntStack {
    var items = [Int]()
    
    // mutating 修饰可以在结构体或枚举中修改属性值,否则编译器报错
    mutating func push(item:Int) {
        items.append(item)
    }
    
    mutating func pop() -> Int {
        return items.removeLast()
    }
    
}
  • 定义一个范型栈结构体 如下
struct Stack<Element> {
    var items = [Element]()
    
    mutating func push(item:Element) {
        items.append(item)
    }
    
    mutating func push() -> Element {
        return items.removeLast()
    }
}
var stackOfStrings = Stack<String>()
stackOfStrings.push(item: "uno")
stackOfStrings.push(item: "dos")
stackOfStrings.push(item: "tres")
stackOfStrings.push(item: "cuatro")
let fromTheTop = stackOfStrings.push() // cuatro
       
if let topItem = stackOfStrings.topItem {
    print(topItem) // tres
}
  • 定义一个协议
protocol Container {
    associatedtype Item // 在协议中不支持 <T> 这个书写方式,要使用 associatedtype 声明
    mutating func append(item:Item)
    var count:Int{get}
    subscript(i:Int)->Item {get}
}
struct Stack<Element> : Container {
    var items = [Element]()
    
    var topItem:Element? {
        return items.isEmpty ? nil : items.last
    }
    
    mutating func push(item:Element) {
        items.append(item)
    }
    
    mutating func push() -> Element {
        return items.removeLast()
    }
    
    // 实现 Container 协议
    var count: Int {
        return items.count
    }
    
    mutating func append(item: Element) {
        self.push(item: item)
    }
    
    subscript(i: Int) -> Element {
        return items[i]
    }
    
}