Swift 泛型

泛型实例1

import UIKit

// 泛型实例1
func swapTwoInt(inout a: Int, inout b: Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

func swapTwoStrings(inout a: String, inout b: String) {
    let temporaryA = a
    a = b
    b = temporaryA
}

func swapTwoDouble(inout a: Double, inout b: Double) {
    let temporaryA = a
    a = b
    b = temporaryA
}

func swapTwoValues<T>(inout a: T, inout b: T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

print("泛型实例1")

var someInt = 3
var anotherInt = 107
swapTwoValues(&someInt, b: &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")

var someString = "hello"
var anotherString = "world"
swapTwoValues(&someString, b: &anotherString)
print("someString is now \(someString), and anotherString is now \(anotherString)")

注意: swapTwoInt、swapTwoStrings、swapTwoDouble 函数,实现体都一样,唯一不同的是参数类型,所以可以用泛型实现swapTwoValues 搞定
console log 如下


泛型实例1.png

泛型实例2

// 泛型实例2
struct IntStack {
    var items = [Int]()
    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 pop() -> Element {
        return items.removeLast()
    }
}

var stackOfString = Stack<String>()
stackOfString.push("Jack")
stackOfString.push("Love")
stackOfString.push("Yao")

print("泛型实例2")
let fromTheTop = stackOfString.pop()
print("fromTheTop is equal to \(fromTheTop)")

var stackOfInt = Stack<Int>()
stackOfInt.push(1992)
stackOfInt.push(8)
stackOfInt.push(5)
stackOfInt.push(520)

let topOfTheInt = stackOfInt.pop()
print("topOfTheInt is \(topOfTheInt)")

console log 如下


泛型实例2.png

扩展泛型参数的使用

// 扩展泛型参数的使用
extension Stack {
    var topItem: Element? {
        return items.isEmpty ? nil : items[items.count - 1]
    }
}

print("扩展泛型参数的使用")
if let topItem = stackOfString.topItem {
    print("The top item on the stack is \(topItem).")
}

console log 如下


扩展泛型参数的使用.png

泛型中的参数类型限制

// 泛型中的参数类型限制
func findStringIndex(ofString valueToFind: String, in array: [String]) -> Int? {
    for (index, value) in array.enumerate() {
        if value == valueToFind {
            return index
        }
    }
    
    return nil
}

print("泛型中的参数类型限制")
let strings = ["cat", "dog", "pig", "monkey"]
if let foundIndex = findStringIndex(ofString: "monkey", in: strings) {
    print("The index of monkey is \(foundIndex)")
}

func findIndex<T: Equatable>(of valueToFind: T, in array: [T]) -> Int? {
    for (index, value) in array.enumerate() {
        if value == valueToFind {
            return index
        }
    }
    
    return nil
}

// 泛型中的参数需要遵守Equatable 协议,以保证参数可以使用==运算符进行比较
if let intIndex = findIndex(of: 1992, in: [1992, 1986, 520]) {
    print("The index of 1992 is \(intIndex)")
}

if let stringIndex = findIndex(of: "💞💞💞", in: ["Jack", "💞💞💞", "Yao"]) {
    print("The index of 💞💞💞 is \(stringIndex)")
}

注意: findIndex泛型中的参数需要遵守Equatable 协议,以保证参数可以使用==运算符进行比较
console log 如下


泛型中的参数类型限制.png

泛型实例3

// 泛型实例3
// associatedtype 关键字在协议中的使用指定参数类型
protocol Container {
    associatedtype ItemType
    mutating func append(item: ItemType)
    var count: Int {
        get
    }
    
    subscript(i: Int) -> ItemType {
        get
    }
}

struct AnotherIntStack: Container {
    var items = [Int]()
    mutating func push(item: Int) {
        items.append(item)
    }
    
    mutating func pop() -> Int {
        return items.removeLast()
    }
    
    typealias ItemType = Int
    mutating func append(item: ItemType) {
        self.push(item)
    }
    
    var count: Int {
        return items.count
    }
    
    subscript(i: Int) -> Int {
        return items[i]
    }
}

struct AnotherStack<Element>: Container {
    var items = [Element]()
    mutating func push(item: Element) {
        items.append(item)
    }
    
    mutating func pop() -> Element {
        return items.removeLast()
    }
    
    mutating func append(item: Element) {
        self.push(item)
    }
    
    var count: Int {
        return items.count
    }
    
    subscript(i: Int) -> Element {
        return items[i]
    }
}

// 扩展现有的数组遵守Container 协议
extension Array: Container {
    
}

// where 语句的使用
func allItemsMatch<C1: Container, C2: Container where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>(someContainer: C1, anotherContainer: C2) -> Bool {
    if someContainer.count != anotherContainer.count {
        return false
    }
    
    for i in 0..<someContainer.count {
        if someContainer[i] != anotherContainer[i] {
            return false
        }
    }
    
    return true
}

var anotherStockOfStrings = AnotherStack<String>()
anotherStockOfStrings.append("Jack")
anotherStockOfStrings.append("Love")
anotherStockOfStrings.append("Yao")

print("泛型实例3")
var arrayOfStrings = ["Jack", "Love", "Yao"]
if allItemsMatch(anotherStockOfStrings, anotherContainer: arrayOfStrings) {
    print("All items match.")
} else {
    print("Not all items match.")
}

console log 如下


泛型实例3.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 泛型代码可以确保你写出灵活的,可重用的函数和定义出任何你所确定好的需求的类型。你的可以写出避免重复的代码,并且用一...
    iOS_Developer阅读 4,196评论 0 0
  • Swift 提供了泛型让你写出灵活且可重用的函数和类型。Swift 标准库是通过泛型代码构建出来的。Swift 的...
    零度_不结冰阅读 3,051评论 0 0
  • 本文转载自http://blog.csdn.net/youshaoduo/article/details/5486...
    desunire阅读 5,908评论 0 0
  • 泛型: 泛型是一种类型的占位符,具体的类型将会在之后被填充。由于Swift的严格类型检验,这是很有用的。在不能或者...
    小松树先生阅读 3,989评论 0 3
  • 附上Apple文档翻译版 1.为什么需要泛型的使用 其实说白了很简单。就是对于方法结构相同,但是由于类型不同,而需...
    mdiep阅读 2,548评论 0 4