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.

------------------越是喧嚣的世界,越需要宁静的思考------------------ 合抱之木,生于毫末;九层之台,起于垒土;千里之行,始于足下。 积土成山,风雨兴焉;积水成渊,蛟龙生焉;积善成德,而神明自得,圣心备焉。故不积跬步,无以至千里;不积小流,无以成江海。骐骥一跃,不能十步;驽马十驾,功在不舍。锲而舍之,朽木不折;锲而不舍,金石可镂。蚓无爪牙之利,筋骨之强,上食埃土,下饮黄泉,用心一也。蟹六跪而二螯,非蛇鳝之穴无可寄托者,用心躁也。