美文网首页
Swift 中的泛型

Swift 中的泛型

作者: 孤雁_南飞 | 来源:发表于2021-03-16 19:38 被阅读0次
  • 泛型函数的定义
  1. 泛型函数可以用于任何类型。
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
    let temp = a
    a = b
    b = temp
}
  • 类型形式参数
  1. 上面的函数中,占位符类型 T 就是一个类型形式参数的例子。类型形式参数指定并且命名一个占位符类型,紧挨着卸载函数名后面的一对尖括号里(比如<T>)
  2. 一旦你指定了一个类型形式参数,你就可以用它定义一个函数形式参数
  3. 你可以通过在尖括号里写多个用逗号隔开的类型形式参数名,来提供更多类型形式参数。
  • 命名类型形式参数
  1. 大多数情况下,类型形式参数的名称都要有描述性,比如 Dictionary<Key, Value> 中的 Key 和 Value,借此告诉读者类型形式参数和泛型类型、泛型用到的函数之间的关系。但是,他们之间的关系没有意义时,一般按惯例用单个字母名字,比如 T U V
  2. 类型形式参数永远用大写开头的驼峰命名法命名,以致命他们是一个类型的占位符,不是一个值
  • 泛型类型
  1. 除了泛型函数,Swift 允许你定义自己的泛型类型。他们是可以用于任意类型的自定义类、结构体、枚举,和 Array、Dictionary 方法类似。
struct Stack<Element> {
    var items = [Element]()
    mutating func push(_ item: Element) {
        items.append(item)
    }
    mutating func pop() -> Element {
        return items.removeLast()
    }
}
var stackOfStrings = Stack<String>()
stackOfStrings.push("one")
stackOfStrings.push("two")
stackOfStrings.push("three")
stackOfStrings.push("four")
  • 扩展泛型类型
  1. 当你扩展一个泛型类型时,不需要在扩展的定义中提供类型形式参数列表。原始类型定义的类型形式参数列表,在扩展提里仍然有效,并且原始类型形式参数列表名称也用于扩展类型形式参数。
extension Stack {
    var topItem: Element? {
        return items.isEmpty ? nil : items[items.count - 1]
    } 
}
  • 类型约束
  1. swapTwoValues(::) 函数和 Stack 类型可以用于任意类型。但是,有时在用于泛型函数的类型和泛型类型上,强制其遵循特定的类型约束很有用。类型约束支出一个类型形式参数必须继承自特定类,或者遵循一个特定的协议、组合协议。
  • 类型约束语法
  1. 在一个类型形式参数名称后面防止一个类或者协议作为形式参数列表的一部分,并用冒号隔开,以写出一个类型约束。
  2. Swift 标准库中定义了一个叫做 Equatable 的协议,要求遵循其协议的类型要实现操作符 (==) 和不相等操作符 (!=), 用于比较该类型的任意两个值。所有 Swift 标准库中的类型自动支持 Equatable 协议。
  3. 任何 Equatable 的类型都能安全地用于函数,因为可以保证哪些类型支持相等操作符。为了表达这个事实,当你定义函数时将 Equatable 类型约束作为类型形式参数定义的一部分书写;
func findIndex<T: Equatable>(of valueToFind: T, in array: [T]) -> Int? {
    for (index, value) in array.enumerated() {
        if value == valueToFind {
            return index
        }
    }
    return nil
}
let names = ["one", "two", "three"]
print(findIndex(of: "two", in: names))

泛型的定义要求:where子句

  • where子句
  1. 如果类型约束中描述的一样,类型约束允许你在泛型类型相关的类型形式参数上定义要求。
  2. 类型约束在为关联类型定义要求时也很有用。通过定义一个泛型 where 子句来实现。泛型 where 子句让你能够要求一个关联类型必须遵循指定的协议,或者指定的类型形式参数和关联类型必须相同。泛型 where 子句以 where 关键字开头,后接关联类型的约束或类型和关联类型一致的关系。泛型 where 子句卸载一个类型或函数体的左半个大括号前面。
protocol Container {
    associatedtype ItemType//: Equatable
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}
func allItemsMath<C1: Container, C2: Container>(_ someContainer: C1, _ anotherContainer: C2) -> Bool where C1.ItemType == C2.ItemType, C1.ItemType: Equatable {
    if someContainer.count != anotherContainer.count {
        return false
    }
    for index in 0..<someContainer.count {
        if someContainer[index] != anotherContainer[index] {
            return false
        }
    }
    return true
}
  • 带有泛型 where 子句的扩展
  1. 你同时也可以使用泛型的 where 子句来作为扩展的一部分
protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}

struct Stack<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]
    }
}
extension Stack where Element: Equatable {
    func isTop(_ item: Element) -> Bool {
        guard let topItem = items.last else {
            return false
        }
        return topItem == item
    }
}
protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
}
extension Container where ItemType: Equatable {
    func startsWith(_ item: ItemType) -> Bool {
        return count >= 1 && self[0] == item
    }
}
extension Container where ItemType == Double {
    func average() -> Double {
        var sum = 0.0
        for index in 0..<count {
            sum += self[index]
        }
        return sum / Double(count)
    }
}

关联类型的泛型 where 子句
你可以在关联类型中包含一个泛型 where 子句。比如说:假定你想要做一个包含遍历器的 Container,比如标准库中 Sequence 协议那样

protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get }
    
    associatedtype Iterator: IteratorProtocol where Iterator.Element == ItemType
    func makeIterator() -> Iterator
}

protocol ComparableContainer: Container where ItemType: Comparable { }

泛型下标

  1. 下标可以使泛型,他们可以包含泛型 where 子句。你可以在 subscript 后用尖括号来写类型占位符,你还可以在下标代码块花括号前些泛型 where 分句。
protocol Container {
    associatedtype ItemType
    mutating func append(_ item: ItemType)
    var count: Int { get }
    subscript(i: Int) -> ItemType { get } 
}

extension Container {
    subscript<Indices: Sequence>(indices: Indices) -> [ItemType] where Indices.Iterator.Element == Int {
        var result = [ItemType]()
        for index in indices {
            result.append(self[index])
        }
        return result
    }
}

相关文章

  • [ WWDC2018 ] - Swift 泛型 Swift Ge

    Swift 泛型历史 我们首先来回顾一下 Swift 中对于泛型支持的历史变更,看看现在在 Swift 中,泛型都...

  • 使用Web浏览器编译Swift代码,及Swift中的泛型

    使用Web浏览器编译Swift代码,及Swift中的泛型 使用Web浏览器编译Swift代码,及Swift中的泛型

  • swift 泛型

    Swift-泛型学习和实例总结 - Mazy's Blog - CSDN博客 Swift中的泛型 - 简书

  • 2021-12-01

    swift5基本语法-泛型函数和泛型类型 Swift中泛型可以将类型参数化,提高代码复用率,减少代码量。 一、泛型...

  • Swift中泛型的使用

    在使用Swift开发的过程中,我们可能经常会碰到泛型。那么究竟什么是泛型?泛型作为Swift最为强大的特性之一,该...

  • swift4 泛型(一)

    swift 泛型 OC 是没有泛型也不支持命命空间的,但是swift中这两者都有,本章主要介绍 泛型 对于iOS开...

  • 泛型

    泛型 1.为什么要有泛型?2.泛型有什么好处?3.Swift泛型语法4.泛型的使用 为什么要有泛型 在编程世界中,...

  • Swift-泛型笔记

    Swift 泛型 Swift 提供了泛型让你写出灵活且可重用的函数和类型。 Swift 标准库是通过泛型代码构建出...

  • Swift 运用协议泛型封装网络层

    Swift 运用协议泛型封装网络层 Swift 运用协议泛型封装网络层

  • 【Swift】泛型常见使用

    1、Swift泛型4种 泛型函数泛型类型泛型协议泛型约束 2、泛型约束3种 继承约束:泛型类型 必须 是某个类的子...

网友评论

      本文标题:Swift 中的泛型

      本文链接:https://www.haomeiwen.com/subject/kdtjcltx.html