1. 程式人生 > >泛型約束-swift

泛型約束-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 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.