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.
- extension Stack where Element: Equatable {
- func isTop(_ item: Element) -> Bool {
- guard let topItem = items.last else {
- return false
- }
- return topItem == item
- }
- }
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 where
clause, 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.
原文地址:https://www.cnblogs.com/feng9exe/p/10111606.html