總結:
1、類型約束只能添加到泛型參量上面
2、關聯類型是泛型參量;
3、關聯類型可以通過 協議.關聯類型名稱的形式引用;
- func allItemsMatch<C1: Container, C2: Container>
- (_ someContainer: C1, _ anotherContainer: C2) -> Bool
- where C1.Item == C2.Item, C1.Item: Equatable
4、約束的語法有兩種:1)繼承類語法 2)where語句語法;
繼承類語法是約束語法的簡化形式,適用於繼承和符合語句的形式:
public struct Tuple<A: Equatable, B: Equatable>
直接把約束添加到類型參量的聲明中;
where語句形式的約束有兩重作用:
1)增加可讀性;將約束從主聲明中剝離;
2)添加非繼承形式的約束和復雜的約束功能
where T == Rule.RowValueType
associatedtype Iterator: IteratorProtocol where Iterator.Element == Item
public extension Request where Response == Void
public extension Thenable where T: Sequence, T.Iterator.Element: Comparable
https://docs.swift.org/swift-book/LanguageGuide/Generics.html#ID553
'where' clause cannot be attached to a non-generic declaration
Type Constraints
Type constraints specify that a type parameter must inherit from a specific class, or conform to a particular protocol or protocol composition.
For example, Swift’s Dictionary type places a limitation on the types that can be used as keys for a dictionary. As described in Dictionaries, the type of a dictionary’s keys must be hashable. That is, it must provide a way to make itself uniquely representable. Dictionary needs its keys to be hashable so that it can check whether it already contains a value for a particular key. Without this requirement, Dictionary could not tell whether it should insert or replace a value for a particular key, nor would it be able to find a value for a given key that is already in the dictionary.
public struct Dictionary<Key, Value> where Key : Hashable
- protocol Container {
- associatedtype Item
- mutating func append(_ item: Item)
- var count: Int { get }
- subscript(i: Int) -> Item { get }
- associatedtype Iterator: IteratorProtocol where Iterator.Element == Item
- func makeIterator() -> Iterator
- }
protocol ComparableContainer: Container where Item: Comparable { }
- func allItemsMatch<C1: Container, C2: Container>
- (_ someContainer: C1, _ anotherContainer: C2) -> Bool
- where C1.Item == C2.Item, C1.Item: Equatable
- func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
- // function body goes here
- }
public struct Tuple<A: Equatable, B: Equatable> {
public let a: A
public let b: B
public init(a: A, b: B) {
self.a = a
self.b = b
}
}
protocol ComparableContainer: Container where Item: Comparable { }
protocol BatchedCollectionType: Collection {
associatedtype Base: Collection
}