swift中的泛型

本文探讨了Swift中的参数泛型应用、类型约束在类和协议中的使用,以及泛型在数据结构(如栈)和关联类(如Container协议)中的实践。通过实例展示了如何在Person协议和Student、fClass类中运用类型约束,以及如何创建和操作泛型栈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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])
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值