码迷,mamicode.com
首页 > 编程语言 > 详细

泛型约束-swift

时间:2018-12-13 01:09:44      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:部分   turn   compare   cut   pre   访问控制   iter   def   code   

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.

泛型约束-swift

标签:部分   turn   compare   cut   pre   访问控制   iter   def   code   

原文地址:https://www.cnblogs.com/feng9exe/p/10111606.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!