函数的泛型约束是函数签名的一部分,不符合约束的初始调用将不能查找到函数(报错)
- Type constraints, as described in Type Constraints, enable you to define requirements on the type parameters associated with a generic function, subscript, or type.
- func allItemsMatch<C1: Container, C2: Container>
- (_ someContainer: C1, _ anotherContainer: C2) -> Bool
- where C1.Item == C2.Item, C1.Item: Equatable {
- // Check that both containers contain the same number of items.
- if someContainer.count != anotherContainer.count {
- return false
- }
- // Check each pair of items to see if they're equivalent.
- for i in 0..<someContainer.count {
- if someContainer[i] != anotherContainer[i] {
- return false
- }
- }
- // All items match, so return true.
- return true
- }
The following requirements are placed on the function’s two type parameters:
C1
must conform to theContainer
protocol (written asC1: Container
).C2
must also conform to theContainer
protocol (written asC2: Container
).- The
Item
forC1
must be the same as theItem
forC2
(written asC1.Item == C2.Item
). - The
Item
forC1
must conform to theEquatable
protocol (written asC1.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.
我思故我在