It will take about 3 minutes to finish reading this article.
In Swift, When defining a protocol, we can’t use generics in a protocol as in a class. The following code is incorrect and will be reported as an error.
Example Code
1 | protocol Stackble <Element> { |
Therefore, associated types can solve this problem in Swift. It’s sometimes useful to declare one or more associated types as part of the protocol’s definition. An associated type gives a placeholder name to a type that’s used as part of the protocol. The actual type to use for that associated type isn’t specified until the protocol is adopted. Associated types are specified with the associatedtype keyword.
Example Code
1 | protocol Stackble { |
Associated types can be applied in situations as follows:
1. Associated type be replaced by concrete type
Example Code
1 | class StringStack: Stackble { |
Thanks to Swift’s type inference, we don’t actually need to declare a concrete Element of String as part of the definition of StringStack.
2. Associated type be replaced by generic type
In a class with generics, generic types replace association types.
Example Code
1 | class Stack <E>: Stackble { |
3. Points for Attention
A protocol contains associated types cannot be used as return values and function parameters.
1 | protocol Runnable { |
The following is the code of compilation error.
1 | protocol Runnable { |
We can fix this point just by a generic Type that conform to the protocol.
1 | func get<T:Runnable>(_ type:Int)-> T { |
Reference
[1] https://docs.swift.org/swift-book/LanguageGuide/Generics.html
[2] https://blog.csdn.net/boildoctor/article/details/113116245