泛型 #

一、泛型概述 #

泛型是Swift强大的特性,允许编写灵活、可复用的代码。

1.1 泛型优势 #

  • 代码复用
  • 类型安全
  • 减少重复代码
  • 提高抽象能力

二、泛型函数 #

2.1 基本语法 #

swift
func swapValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}

var x = 1
var y = 2
swapValues(&x, &y)
print("x: \(x), y: \(y)")

var a = "Hello"
var b = "World"
swapValues(&a, &b)
print("a: \(a), b: \(b)")

2.2 多类型参数 #

swift
func pair<A, B>(_ first: A, _ second: B) -> (A, B) {
    return (first, second)
}

let result = pair(1, "Hello")
print(result)

2.3 返回泛型 #

swift
func makeArray<T>(_ element: T, count: Int) -> [T] {
    return Array(repeating: element, count: count)
}

let strings = makeArray("Hi", count: 3)
let numbers = makeArray(42, count: 5)

print(strings)
print(numbers)

三、泛型类型 #

3.1 泛型结构体 #

swift
struct Stack<Element> {
    private var items: [Element] = []
    
    var isEmpty: Bool {
        return items.isEmpty
    }
    
    var count: Int {
        return items.count
    }
    
    mutating func push(_ item: Element) {
        items.append(item)
    }
    
    mutating func pop() -> Element? {
        return items.popLast()
    }
    
    func peek() -> Element? {
        return items.last
    }
}

var intStack = Stack<Int>()
intStack.push(1)
intStack.push(2)
print(intStack.pop() ?? 0)

var stringStack = Stack<String>()
stringStack.push("Hello")
print(stringStack.pop() ?? "")

3.2 泛型类 #

swift
class Container<T> {
    private var items: [T] = []
    
    func add(_ item: T) {
        items.append(item)
    }
    
    func get(at index: Int) -> T? {
        guard index >= 0 && index < items.count else { return nil }
        return items[index]
    }
    
    func getAll() -> [T] {
        return items
    }
}

let container = Container<Int>()
container.add(1)
container.add(2)
print(container.getAll())

3.3 泛型枚举 #

swift
enum Result<Success, Failure: Error> {
    case success(Success)
    case failure(Failure)
}

let success: Result<Int, Error> = .success(42)
let failure: Result<Int, Error> = .failure(NSError(domain: "", code: -1))

四、类型约束 #

4.1 基本约束 #

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

let index = findIndex(of: 3, in: [1, 2, 3, 4, 5])
print(index ?? -1)

4.2 多约束 #

swift
func process<T: Comparable & Hashable>(_ value: T) {
    print(value)
}

process(42)
process("Hello")

4.3 where子句 #

swift
func allEqual<T>(_ array: [T]) -> Bool where T: Equatable {
    guard let first = array.first else { return true }
    return array.allSatisfy { $0 == first }
}

print(allEqual([1, 1, 1]))
print(allEqual([1, 2, 3]))

五、关联类型 #

5.1 基本用法 #

swift
protocol Container {
    associatedtype Item
    var count: Int { get }
    mutating func append(_ item: Item)
    subscript(i: Int) -> Item { get }
}

struct IntStack: Container {
    typealias Item = Int
    
    private var items: [Int] = []
    
    var count: Int { return items.count }
    
    mutating func append(_ item: Int) {
        items.append(item)
    }
    
    subscript(i: Int) -> Int {
        return items[i]
    }
}

5.2 类型推断 #

swift
struct GenericStack<Element>: Container {
    private var items: [Element] = []
    
    var count: Int { return items.count }
    
    mutating func append(_ item: Element) {
        items.append(item)
    }
    
    subscript(i: Int) -> Element {
        return items[i]
    }
}

5.3 关联类型约束 #

swift
protocol Container {
    associatedtype Item: Equatable
    var count: Int { get }
    mutating func append(_ item: Item)
    subscript(i: Int) -> Item { get }
    
    func indexOf(_ item: Item) -> Int?
}

extension Container {
    func indexOf(_ item: Item) -> Int? {
        for (index, value) in enumerated() {
            if value == item {
                return index
            }
        }
        return nil
    }
}

六、泛型扩展 #

6.1 扩展泛型类型 #

swift
extension Stack {
    var top: Element? {
        return items.last
    }
    
    func map<U>(_ transform: (Element) -> U) -> Stack<U> {
        var result = Stack<U>()
        for item in items {
            result.push(transform(item))
        }
        return result
    }
}

6.2 条件扩展 #

swift
extension Stack where Element: Equatable {
    func contains(_ item: Element) -> Bool {
        return items.contains(item)
    }
}

extension Stack where Element: Numeric {
    func sum() -> Element {
        return items.reduce(0, +)
    }
}

七、实际应用 #

7.1 泛型网络请求 #

swift
struct APIResponse<T: Decodable>: Decodable {
    let code: Int
    let message: String
    let data: T?
}

struct User: Decodable {
    let id: Int
    let name: String
}

func fetch<T: Decodable>(url: URL, completion: @escaping (Result<T, Error>) -> Void) {
    URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error == nil else {
            completion(.failure(error!))
            return
        }
        
        do {
            let decoded = try JSONDecoder().decode(T.self, from: data)
            completion(.success(decoded))
        } catch {
            completion(.failure(error))
        }
    }.resume()
}

7.2 泛型缓存 #

swift
class Cache<Key: Hashable, Value> {
    private var storage: [Key: Value] = [:]
    
    func set(_ value: Value, forKey key: Key) {
        storage[key] = value
    }
    
    func get(_ key: Key) -> Value? {
        return storage[key]
    }
    
    func remove(_ key: Key) {
        storage.removeValue(forKey: key)
    }
    
    func clear() {
        storage.removeAll()
    }
}

let cache = Cache<String, Int>()
cache.set(42, forKey: "answer")
print(cache.get("answer") ?? 0)

八、总结 #

本章学习了Swift泛型:

  • 泛型函数:参数化类型
  • 泛型类型:结构体、类、枚举
  • 类型约束:限制类型
  • 关联类型:协议中的泛型

最佳实践:

  • 使用泛型提高代码复用
  • 合理使用类型约束
  • 使用关联类型定义协议
  • 扩展泛型类型添加功能

下一章,我们将学习错误处理!

最后更新:2026-03-26