泛型实例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 如下
泛型实例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 如下
扩展泛型参数的使用
// 扩展泛型参数的使用
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 如下
泛型中的参数类型限制
// 泛型中的参数类型限制
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 如下
泛型实例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 如下