zoukankan      html  css  js  c++  java
  • 泛型约束-swift

    1、泛型定义本体有参量类型约束;

    2、泛型扩展对参量类型约束;

    3、函数参量约束;

    泛型类型的访问控制:

    1、与类型无关的通用函数,泛型的任何实例都可以访问;

    2、与类型有关的函数(通过扩展约束实现),只有特定类型实例化的泛型实例才能访问;

    由此得出结论:

    再考虑泛型约束的情况下,泛型类型是一个代码复用家族;

    1、与类型无关的部分为顶级泛型;

    2、参量类型为继承(符合)关系的约束泛型为二级泛型;

    3、参量类型为具体类型的泛型为具体泛型;

    在考虑泛型约束的情况下,泛型函数的访问控制由泛型和参量类型共同决定;

    不符合共同决定的情况,会被编译器否定(报错)。

    https://docs.swift.org/swift-book/LanguageGuide/Generics.html#ID553

     

    Extensions with a Generic Where Clause

    You can also use a generic where clause as part of an extension. The example below extends the generic Stack structure from the previous examples to add an isTop(_:) method.

    1. extension Stack where Element: Equatable {
    2. func isTop(_ item: Element) -> Bool {
    3. guard let topItem = items.last else {
    4. return false
    5. }
    6. return topItem == item
    7. }
    8. }

    This new isTop(_:) method first checks that the stack isn’t empty, and then compares the given item against the stack’s topmost item. If you tried to do this without a generic whereclause, you would have a problem: The implementation of isTop(_:) uses the == operator, but the definition of Stack doesn’t require its items to be equatable, so using the == operator results in a compile-time error. Using a generic where clause lets you add a new requirement to the extension, so that the extension adds the isTop(_:) method only when the items in the stack are equatable.

  • 相关阅读:
    CSS框模型,浮动,定位以及其他属性
    CSS基础知识点总结
    Html基础知识点
    CentOS7桌面版系统使用的一些小技巧
    win 执行puppet
    常用脚本总结
    Ansible小记
    Tampermonkey-让百度云下载飞起来
    安装zabbix 遇到的一些问题
    alias
  • 原文地址:https://www.cnblogs.com/feng9exe/p/10111606.html
Copyright © 2011-2022 走看看