1. 对参数泛型
// 1. 交换变量
func swapTwoInt(_ a: inout Int, _ b: inout Int) {
// swap(&a, &b)
let temp = a
a = b
b = temp
}
func swapTwoStr(_ a: inout Int, _ b: inout Int) {
let temp = a
a = b
b = temp
}
func swapTwoValue<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
//------------------------------------------------
2. 类型约束
class Person {
let name: String = "张三"
}
protocol testProtocol {
func test()
}
class Student: Person {
}
class fClass: testProtocol {
func test() {
print("test")
}
}
// 2 类型约束
func someFunction<T: Person, U: testProtocol>(someT: T, someU: U) {
print(someT.name)
someU.test()
}
/**
在需要的地方调用如下:
fanxing().someFunction(someT: Student(), someU: fClass())
打印结果:
张三
test
*/
3. 泛型类型
// 3 对栈进行泛型
struct IntStack {
var items = [Int]()
mutating func push(_ item: Int) {
items.append(item)
}
mutating func pop(_ item: Int) -> Int {
return items.removeLast()
}
}
struct Stack<T> {
var items = [T]()
mutating func push(_ item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
extension Stack {
var topItem: T? {
return items.isEmpty ? nil : items[items.count - 1]
}
}
//------------------------------------------------
4. 关联类
声明某个协议,里面也需要泛型
//4. 关联类
protocol Container {
associatedtype ItemType
mutating func append(_ item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
struct StackAss<T>: Container {
typealias ItemType = T
var items = [T]()
mutating func push(_ item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
// Container
mutating func append(_ item: ItemType) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> T {
return items[i]
}
}
/**
使用如下:
var stackAss = StackAss<String>()
stackAss.push("a")
stackAss.append("b")
stackAss.push("c")
print(stackAss.count)
print(stackAss.items)
打印结果:
3
["a", "b", "c"]
*/
5. where
- 让Array遵守Container协议
extension Array: Container {
}
func allItemsMatch<C1: Container, C2: Container>(_ oneContainer: C1, _ anotherContainer: C2) -> Bool where C1.ItemType == C2.ItemType, C1.ItemType: Equatable {
if oneContainer.count != anotherContainer.count {
return false
}
for i in 0..<oneContainer.count {
if oneContainer[i] != anotherContainer[i] {
return false
}
}
return true
}
/**
使用:
let arr1 = [1,2,3]
let arr2 = [1,2,3]
let res = allItemsMatch(arr1, arr2)
print(res)
打印结果:
true
*/
迭代器和遍历
var items = [1,2,3]
var itemInerator = items.makeIterator()
while let num = itemInerator.next() {
print(num * 10)
}
for i in items.indices {
print(items[i])
}