函数的泛型约束是函数签名的一部分,不符合约束的初始调用将不能查找到函数(报错)

  1. Type constraints, as described in Type Constraints, enable you to define requirements on the type parameters associated with a generic function, subscript, or type.

 

  1. func allItemsMatch<C1: Container, C2: Container>
  2. (_ someContainer: C1, _ anotherContainer: C2) -> Bool
  3. where C1.Item == C2.Item, C1.Item: Equatable {
  4. // Check that both containers contain the same number of items.
  5. if someContainer.count != anotherContainer.count {
  6. return false
  7. }
  8. // Check each pair of items to see if they're equivalent.
  9. for i in 0..<someContainer.count {
  10. if someContainer[i] != anotherContainer[i] {
  11. return false
  12. }
  13. }
  14. // All items match, so return true.
  15. return true
  16. }

 

The following requirements are placed on the function’s two type parameters:

  • C1 must conform to the Container protocol (written as C1: Container).
  • C2 must also conform to the Container protocol (written as C2: Container).
  • The Item for C1 must be the same as the Item for C2 (written as C1.Item == C2.Item).
  • The Item for C1 must conform to the Equatable protocol (written as C1.Item: Equatable).

The first and second requirements are defined in the function’s type parameter list, and the third and fourth requirements are defined in the function’s generic where clause.

posted @ 2018-12-13 16:52  zzfx  阅读(191)  评论(0编辑  收藏  举报